There are several ways to loop through a plain JavaScript object.

One way is to use a ‘for…in’ loop. This loop iterates over the enumerable properties of an object, and it can be used to loop through an object’s properties. Here’s an example:

let obj = { "name": "John", "age": 30, "city": "New York" };
for (let key in obj) {
   console.log(key + ": " + obj[key]);
}

This will output:

name: John
age: 30
city: New York

Another way is to use Object.keys() method. This method returns an array of a given object’s own enumerable property names, in the same order as we get with a normal loop.

let obj = { "name": "John", "age": 30, "city": "New York" };
Object.keys(obj).forEach(function(key) {
  console.log(key + ": " + obj[key]);
});

This will also output:

name: John
age: 30
city: New York

You can also use ‘Object.entries(obj)’ method and iterate through the array returned, where each element is a key-value pair.

let obj = { "name": "John", "age": 30, "city": "New York" };
for (let [key, value] of Object.entries(obj)) {
  console.log(`${key}: ${value}`);
}

This will also output:

name: John
age: 30
city: New York

It is worth noting that the order of properties of an object is not guaranteed and may not be the same across different JavaScript engines.

Also Read:

Categorized in: