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

How do I get key-value pair from array of JavaScript objects?

本文关键字:获取 键值对 数组 对象 JavaScript      更新时间:2023-09-26

我有

var results = {};

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

({
    "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();
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);

您可以使用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();

使用类似库的下划线怎么样?可以通过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;
});

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

如果执行eval(%yourcode%),它将返回一个具有一个键"result"的对象,该键指向内部只有一个值的数组-一个包含信息对的数组。因此,要访问这些密钥,您必须迭代此对象-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>'); 
}


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

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>'); 
  }
});


哦,如果你想创建一个包含country作为关键字和zipcode作为值的"result"对象,你可以这样做:

// 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>'));


对不起,我终于得到了你需要的)看:

// 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>'));

由于您使用nodejs,因此可以安装字符串存储npm模块。它将它转换为一个数组,并且可以很容易地使用这些值。更多详细信息请点击此处。https://www.npmjs.com/package/stringstore