admin管理员组文章数量:1332389
I have
var results = {};
I wrote code that populates results (from an HTTP GET request) with data in this format:
({
"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.
I'm having trouble accessing keys & values; I always seem to get undefined
. How do I go about accessing the keys?
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',
path: '/json.php?fds=geo/usa/zipcode/'+ JSON.parse(data[i].zip)
};
http.request(options, callback).end();
}
fetch();
I have
var results = {};
I wrote code that populates results (from an HTTP GET request) with data in this format:
({
"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.
I'm having trouble accessing keys & values; I always seem to get undefined
. How do I go about accessing the keys?
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.',
path: '/json.php?fds=geo/usa/zipcode/'+ JSON.parse(data[i].zip)
};
http.request(options, callback).end();
}
fetch();
Share
edited Jun 29, 2015 at 20:23
user1106925
asked Jun 29, 2015 at 16:47
user3583412user3583412
111 gold badge1 silver badge4 bronze badges
2
- How can we know what's wrong if you don't show us your non-working code? – user1106925 Commented Jun 29, 2015 at 16:55
- is your requirement to separate out the values from the populated result? – aashima Commented Jun 29, 2015 at 17:02
5 Answers
Reset to default 1var 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);
You can use lodash library to filter your result.
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();
What about using a library like underscore? The could achieve this with the 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;
});
Take a look at this Plunker: http://plnkr.co/edit/fNOWPYBPsaNNDVX3M904
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:
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:
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>'));
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./package/stringstore
本文标签: nodejsHow do I get keyvalue pair from array of JavaScript objectsStack Overflow
版权声明:本文标题:node.js - How do I get key-value pair from array of JavaScript objects? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742291710a2447923.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论