How do I loop through or enumerate a JavaScript object?

Explanation

To loop through or enumerate a JavaScript object you can use the for_in  loop as we have used before. However, you also have to remember to make sure that the key you get is an actual property of an object. And it does not come from the prototype.

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])
}
 Here one has to note that the use of for-of instead of for-in.if not used it will return undefined on named properties. And Object.keys() is used to ensure that the use of only the object’s own properties without actually holding the whole prototype-chain properties

Here we will use the new Object.entries() method:

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

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

 

 

Also read, How to insert an item into an array at a specific index

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *