Current Article:

How to loop through or enumerate a JavaScript object?

How to loop through or enumerate a JavaScript object?

You can use the for-in loop, but also have to make sure that the key you get is an actual property of an object, and doesn’t come from the prototype.

Example:

var p = {
  "p1": "value1",
  "p2": "value2",
  "p3": "value3"
};

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    console.log(key + " -> " + p[key]);
  }
}