首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从JavaScript对象数组中获取键值对?

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

Stack Overflow用户
提问于 2015-06-30 00:47:41
回答 5查看 21.5K关注 0票数 0

我有过

代码语言:javascript
复制
var results = {};

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

代码语言:javascript
复制
({
    "result":[
    {
        "Longitude" : "-097.722382",
        "Zipcode" : "78751",
        "ZipClass" : "STANDARD",
        "County" : "TRAVIS",
        "City" : "AUSTIN",
        "State" : "TX",
        "Latitude" : "+30.310606"
    }
]}
)

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

我在访问键和值时遇到了问题;我似乎总是得到undefined。我该如何访问这些密钥?

这是我的代码。从本质上讲,我正在处理一堆邮政编码,只过滤掉德克萨斯州的邮政编码。

代码语言:javascript
复制
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();
EN

回答 5

Stack Overflow用户

发布于 2015-06-30 01:06:05

代码语言:javascript
复制
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);
票数 1
EN

Stack Overflow用户

发布于 2018-08-01 14:05:16

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

代码语言:javascript
复制
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();
票数 1
EN

Stack Overflow用户

发布于 2015-06-30 01:04:40

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

代码语言:javascript
复制
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>'); 
}

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

代码语言:javascript
复制
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>'); 
  }
});

哦,如果你想创建一个'result‘对象,这个对象将包含county作为键,zipcode作为值,你可以这样做:

代码语言:javascript
复制
// 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>'));

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

代码语言:javascript
复制
// 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>'));

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31121188

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档