如何从JavaScript对象数组中获取键值对?

时间:2015-06-29 16:47:41

标签: javascript node.js hashmap

我有

var results = {};

我编写的代码使用以下格式的数据填充结果(来自HTTP GET请求):

({
    "result":[
    {
        "Longitude" : "-097.722382",
        "Zipcode" : "78751",
        "ZipClass" : "STANDARD",
        "County" : "TRAVIS",
        "City" : "AUSTIN",
        "State" : "TX",
        "Latitude" : "+30.310606"
    }
]}
)

但是,我希望结果以TRAVIS为键,然后添加另一个名为count的变量,该变量计算该县的总数。

我无法访问密钥&值;我似乎总是undefined。如何访问密钥?

这是我的代码。基本上,我正在浏览一堆邮政编码,只过滤掉德克萨斯州的邮政编码。

var i = 0;
var results = {};



/*
var results = {
  'TRAVIS': 10,
  'DALLAS': 15,
};

*/

function getValues(obj, key) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getValues(obj[i], key));
        } else if (i == key) {
            objects.push(obj[i]);
        }
    }
    return objects;
}




callback = function(response) {
  //console.log('callback('+i+')');
  var str = '';
  response.on('data', function (chunk) {
    str += chunk;
  });



  response.on('end', function () {
      console.log('Processing: ' + i);
      // TODO: Parse JSON
      str = str.replace(/['\(\)]/g, "");
        if(str.substring(0,1) == "{"){

      JSON.parse(str);
}





    if(str.substring(0,1) == "{"){

      if( (str.substring(str.search("\"State\"") + 10, str.search("\"State\"") + 14)) == "\"TX\"")
       {  //console.log("THIS IS FROM TEXAS ");

          results[i] = str; 



       }
     }



    setTimeout(function() {
      i++;
      if (i >= data.length) {
        console.log(results);


      } else {
        fetch();
      }
    }, 1000)
  });
}


function fetch() {
  //console.log('fetch('+i+')');
  var options = {
    host: 'gomashup.com',
    path: '/json.php?fds=geo/usa/zipcode/'+ JSON.parse(data[i].zip)
  };
  http.request(options, callback).end();
}

fetch();

5 个答案:

答案 0 :(得分:0)

如果您执行eval(%yourcode%),它会返回一个对象,该对象有一个键'结果'它指向内部只有一个值的数组 - 一个包含信息对的数组。因此,要访问这些键,您必须迭代此对象 - eval(%yourcode%)['result'][0],如下所示:



initialString = '({"result":[{"Longitude" : "-097.722382","Zipcode" : "78751","ZipClass" : "STANDARD","County" : "TRAVIS","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"}]})';
    
myObj = eval(initialString)['result'][0];

for (key in myObj) { 
  document.write(key + ': ' + myObj[key] + '<br>'); 
}
&#13;
&#13;
&#13;


例如,如果您要让结果对象包含许多对象,则应该遍历(myObj = eval(initialString)['result']),如下所示:

&#13;
&#13;
initialString = '({"result":[{"Longitude" : "1","Zipcode" : "78751","ZipClass" : "STANDARD","County" : "TRAVIS","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"},{"Longitude" : "2","Zipcode" : "78751","ZipClass" : "STANDARD","County" : "TRAVIS","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"},{"Longitude" : "3","Zipcode" : "78751","ZipClass" : "STANDARD","County" : "TRAVIS","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"}]})';
    
myObj = eval(initialString)['result'];

myObj.forEach(function(infoItem,index) {
  document.write('Item #' + (index+1) + "<br>");
  for (key in infoItem) { 
    document.write('&nbsp;&nbsp;&nbsp;&nbsp;' + key + ': ' + infoItem[key] + '<br>'); 
  }
});
&#13;
&#13;
&#13;


哦,如果你想创造&#39;结果&#39;对象将包含县作为键和zipcode作为值,您可以这样做:

&#13;
&#13;
// in this example `myObj` has 3 objects inside itself
// we iterate through each and select values that we need

var initialString = '({"result":[{"Longitude" : "1","Zipcode" : "78751","ZipClass" : "STANDARD","County" : "TRAVIS","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"},{"Longitude" : "2","Zipcode" : "37465","ZipClass" : "STANDARD","County" : "SOMECOUNTY","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"},{"Longitude" : "3","Zipcode" : "90210","ZipClass" : "STANDARD","County" : "MYBELOVEDCOUNTY","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"}]})',
    result = {};

myObj = eval(initialString)['result'];

myObj.forEach(function(infoItem,index) {
  // here we create entries inside 'result' object
  // using county values as keys
  result[infoItem['County']] = infoItem['Zipcode'];
});

document.write(JSON.stringify(result,null,'<br>'));
&#13;
&#13;
&#13;


抱歉,我终于得到了你需要的东西)看:

&#13;
&#13;
// in this example `myObj` has 4 objects inside itself
// we iterate through each and select values that we need

var initialString = '({"result":[{"Longitude" : "1","Zipcode" : "78751","ZipClass" : "STANDARD","County" : "TRAVIS","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"},{"Longitude" : "2","Zipcode" : "37465","ZipClass" : "STANDARD","County" : "SOMECOUNTY","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"},{"Longitude" : "3","Zipcode" : "90210","ZipClass" : "STANDARD","County" : "MYBELOVEDCOUNTY","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"},{"Longitude" : "4","Zipcode" : "90210","ZipClass" : "STANDARD","County" : "MYBELOVEDCOUNTY","City" : "AUSTIN","State" : "TX","Latitude" : "+30.310606"}]})',
    result = {};

myObj = eval(initialString)['result'];

myObj.forEach(function(infoItem,index) {
  // here we create entries inside 'result' object
  // using county value as a keys

  // first we check if an entry with current key exists
  if (result[infoItem['County']]) {
    // if yes, just increment it
    result[infoItem['County']]++;
  } else {
    // if no, make it equal to 1
    result[infoItem['County']] = 1;
  }
});

document.write(JSON.stringify(result,null,'<br>'));
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var response = ({
    "result":[
    {
        "Longitude" : "-097.722382",
        "Zipcode" : "78751",
        "ZipClass" : "STANDARD",
        "County" : "TRAVIS",
        "City" : "AUSTIN",
        "State" : "TX",
        "Latitude" : "+30.310606"
    }
]});

You can excess key and value this way...

console.log(response.result[0].County);
console.log(response.result[0].Zipcode);
And also add a key ......
response.result[0].count = 134;
console.log(response);

答案 2 :(得分:0)

使用像下划线这样的库怎么样?可以使用groupBy and map functions实现此目的。

var grouped = _.groupBy(response.result, function(item){
  return item.County;
});
var result = _.each(grouped, function(value, key, list){
  return list[key] = value.length;
});

看看这个Plunker:http://plnkr.co/edit/fNOWPYBPsaNNDVX3M904

答案 3 :(得分:0)

因为你使用nodejs你可以安装字符串存储npm模块。它将其转换为数组,并且可以轻松使用这些值。这里有更多细节。 https://www.npmjs.com/package/stringstore

答案 4 :(得分:0)

您可以使用lodash库来过滤结果。

let _ = require("lodash");

let res = {
    result: [
        {
            "Longitude": "-097.722382",
            "Zipcode": "78751",
            "ZipClass": "STANDARD",
            "County": "TRAVIS",
            "City": "AUSTIN",
            "State": "TX",
            "Latitude": "+30.310606"
        },
        {
            "Longitude": "-097.722382",
            "Zipcode": "78751",
            "ZipClass": "STANDARD",
            "County": "TRAVIS",
            "City": "AUSTIN",
            "State": "TX",
            "Latitude": "+30.310606"
        },
        {
            "Longitude": "-097.722382",
            "Zipcode": "78751",
            "ZipClass": "STANDARD",
            "County": "abc",
            "City": "AUSTIN",
            "State": "TX",
            "Latitude": "+30.310606"
        }
    ]
}

function test() {
    let groupedResult = _.groupBy(res.result, 'County')
    result = {}
    _.forEach(Object.keys(groupedResult), (County)=>{
        result[County] = groupedResult[County].length
    })
    console.log(result)
}

test();
相关问题