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.com',
path: '/json.php?fds=geo/usa/zipcode/'+ JSON.parse(data[i].zip)
};
http.request(options, callback).end();
}
fetch();