JavaScript - Loop

javascript

How can we loop over the properties of an object?

Use the 'for in' loop:

var obj = {one: 1, two: 2, three: 3};
for (var p in obj) {
  // do something
}

for (myvar in obj) {
  if (obj.hasOwnProperty(myvar)) {
    // ..
  }
}

On each iteration, another property name string from the object is assigned to the variable myvar. The hasOwnProperty method is used to determine whether the property name is truly a member of the object or was found instead on the prototype chain. Think carefully when you use the hasOwnProperty method.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License