0

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();
2
  • How can we know what's wrong if you don't show us your non-working code? Commented Jun 29, 2015 at 16:55
  • is your requirement to separate out the values from the populated result? Commented Jun 29, 2015 at 17:02

5 Answers 5

1
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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but I have a loop that goes through several zip codes. So how would I make this work for all of them? I can't do a generic format with concatenation because I would need to access the keys & values of results, which I can't do right now.
1

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

Comments

0

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

Comments

0

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('&nbsp;&nbsp;&nbsp;&nbsp;' + 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>'));

3 Comments

Thank you. But since it's a loop (the one I posted was just an example), and there are several zip codes, what would I put inside of 's'?
Do I have to start out with actual data? Is there a way I can just do a generic string for initialString? The problem I'm running into again is trying to concatenate str[i].County (for example), but I can't access the keys. If that makes sense.
Look at my answer again) Is that what you need? Actually i can't understand what youre going to achieve)
0

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

1 Comment

Answers to questions should not be contained in links as they will change over time. Leave the link as a reference, but the answer should be migrated to this site if applicable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.