How do I loop through or enumerate a JavaScript object?

ghz 1years ago ⋅ 4701 views

Question

I have a JavaScript object like the following:

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

How do I loop through all of p's elements (p1, p2, p3...) and get their keys and values?


Answer

You can use the [for-in](https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Statements/for...in) loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.

Here is the snippet:

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

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

For-of with Object.keys() alternative:

var p = {
    0: "value1",
    "b": "value2",
    key: "value3"
};

for (var key of Object.keys(p)) {
    console.log(key + " -> " + p[key])
}

Notice the use of [for-of](https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Statements/for...of) instead of [for- in](https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Statements/for...in), if not used it will return undefined on named properties, and [Object.keys()](https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) ensures the use of only the object's own properties without the whole prototype-chain properties

Using the new[Object.entries()](https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) method:

Note: This method is not supported natively by Internet Explorer. You may consider using a Polyfill for older browsers.

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

for (const [key, value] of Object.entries(p)) {
  console.log(`${key}: ${value}`);
}