Sunday, June 7, 2015

JavaScript - iterate or loop over JavaScript object or JSON

It is taken from here: http://stackoverflow.com/questions/684672/loop-through-javascript-object

In JavaScript, every object has a bunch of built-in key-value pairs that have meta-information. When you loop through all the key-value pairs for an object you're looping through them too. hasOwnPropery() filters these out:

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    alert(key + " -> " + p[key]);
  }
}
In ECMAScript 5 you have new approach in iteration fields of literal - Object.keys
More information you can see on MDN
My choice is below as a faster solution in current versions of browsers (Chrome30, IE10, FF25)

var keys = Object.keys(p),
    len = keys.length,
    i = 0,
    prop,
    value;
while (i < len) {
    prop = keys[i];
    value = p[prop];
    i += 1;
}

No comments: