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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (794)

我有

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();
提问于
用户回答回答于

使用像下划线这样的库怎么样?可以通过groupBy和map函数实现这一点。

var grouped = _.groupBy(response.result, function(item){
  return item.County;
});
var result = _.each(grouped, function(value, key, list){
  return list[key] = value.length;
});
用户回答回答于
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);

扫码关注云+社区

领取腾讯云代金券