Loop through objects in JavaScript

Looping through objects in JavaScript involves iterating over the properties (keys) of the object and accessing their corresponding values. There are several methods to achieve this:

For...in Loop

The for...in loop iterates over the enumerable properties of an object, including properties inherited from its prototype chain.

const person = { name: "Harry", age: 30, occupation: "Engineer" }; for (const key in person) { console.log(key, person[key]); }

Object.keys()

The Object.keys() method returns an array of an object's own enumerable property names, which you can then iterate through using a loop.

const person = { name: "Harry", age: 30, occupation: "Engineer" }; const keys = Object.keys(person); for (const key of keys) { console.log(key, person[key]); }

Object.values()

The Object.values() method returns an array of an object's own enumerable property values. You can use this method in combination with a loop to access these values.

const person = { name: "Harry", age: 30, occupation: "Engineer" }; const values = Object.values(person); for (const value of values) { console.log(value); }

Object.entries()

The Object.entries() method returns an array of an object's own enumerable property [key, value] pairs. You can loop through these pairs to access both keys and values.

const person = { name: "Harry", age: 30, occupation: "Engineer" }; const entries = Object.entries(person); for (const [key, value] of entries) { console.log(key, value); }

forEach() Method (for Objects)

While forEach() is often used with arrays, it can also be used for objects with a slight workaround using Object.entries().

const person = { name: "Harry", age: 30, occupation: "Engineer" }; Object.entries(person).forEach(([key, value]) => { console.log(key, value); });

Conclusion

Remember that the order of properties in an object is not guaranteed, so the iteration order might vary between different JavaScript engines. Additionally, the above methods only iterate over an object's own enumerable properties and do not include properties inherited from prototypes.