Bharthan Bharthan - 7 months ago 11
Javascript Question

How to iterate through key/value pair in javascript, if I dont know key name

I have a json like:

var json = [{"Google":[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},
{"Linkedin":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},
{"Uber":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},
{"Akamai":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},
{"Apple":[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0]},
{"Hulu":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},
{"IBM":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},
{"Spotify":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},
{"Amazon":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}];


I want to iterate through it.
json.length returns 9 => implying there are 9 key/value pairs in this json. How can I find key at index 0 and its corresponding value in javascript.

I tried using something like:

$.each(json, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});


but here key is returning 1,2,3... and value as [object object]

Answer

Use .forEach to iterate through the array and Object.keys over iterated item to get all the keys of individual object.

var json = [{
  "Google": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
  "Linkedin": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
  "Uber": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
  "Akamai": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
  "Apple": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
}, {
  "Hulu": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
  "IBM": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
  "Spotify": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
  "Amazon": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}];
json.forEach(function(item) {
  var keys = Object.keys(item);
  console.log(keys);
  //to get the values
  keys.forEach(function(key) {
    console.log(item[key]);
  })
});
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Comments