如何从 JavaScript 对象数组中获取键值对?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31121188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get key-value pair from array of JavaScript objects?
提问by user3583412
I have
我有
var results = {};
I wrote code that populates results (from an HTTP GET request) with data in this format:
我编写了使用以下格式的数据填充结果(来自 HTTP GET 请求)的代码:
({
"result":[
{
"Longitude" : "-097.722382",
"Zipcode" : "78751",
"ZipClass" : "STANDARD",
"County" : "TRAVIS",
"City" : "AUSTIN",
"State" : "TX",
"Latitude" : "+30.310606"
}
]}
)
However, I want results to have TRAVIS
as a key, and then add another variable called count
, which counts how many total are in that county.
但是,我希望将结果TRAVIS
作为键,然后添加另一个名为 的变量count
,该变量计算该县的总数。
I'm having trouble accessing keys & values; I always seem to get undefined
. How do I go about accessing the keys?
我在访问键和值时遇到问题;我似乎总是得到undefined
。我该如何访问密钥?
Here's my code. Essentially, I'm going through a bunch of zip codes, filtering out only the ones that are in Texas.
这是我的代码。本质上,我正在浏览一堆邮政编码,仅过滤掉德克萨斯州的邮政编码。
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();
回答by lucifer63
If you do eval(%yourcode%)
, it will return you an object which has one key 'result' which is pointing at array with only one value inside - an array with your info pairs. So to access these keys, you have to iterate this object - eval(%yourcode%)['result'][0]
, like this:
如果这样做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>');
}
For example, if you gonna have your result object to contain many objects, you should iterate through (myObj = eval(initialString)['result'])
, like this:
例如,如果你(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(' ' + key + ': ' + infoItem[key] + '<br>');
}
});
Oh, if you want to create 'result' object which will contain county as key and zipcode as value, you can do it this way:
哦,如果你想创建包含县作为键和邮政编码作为值的“结果”对象,你可以这样做:
// 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>'));
Sorry, i finally got what you need) Look:
对不起,我终于得到了你需要的东西)看:
// 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>'));
回答by Md Atiqul Haque
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);
回答by despuestambien
What about using a library like underscore? The could achieve this with the groupBy and map functions.
使用像下划线这样的库怎么样?可以通过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;
});
Take a look at this Plunker: http://plnkr.co/edit/fNOWPYBPsaNNDVX3M904
看看这个Plunker:http://plnkr.co/edit/fNOWPYBPsaNNDVX3M904
回答by joedavid
since youre using nodejs you could install the string store npm module. It converts it into an array and the values can be used easily. more details here. https://www.npmjs.com/package/stringstore
由于您使用的是 nodejs,因此您可以安装字符串存储 npm 模块。它将其转换为数组,并且可以轻松使用这些值。更多细节在这里。 https://www.npmjs.com/package/stringstore
回答by Rahul Patil
You can use lodash library to filter your result.
您可以使用 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();