iterate key value object javascript

Iterating through a key-value object in JavaScript is relatively straightforward. It can be done using either a for-in loop or the Object.entries() method. Both of these approaches provide an easy way to loop through an object's key-value pairs and access the corresponding values.


// Using a for-in loop
for (const key in obj) {
    const value = obj[key];
    console.log(`${key}: ${value}`);
}

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

In the case of a for-in loop, the key-value pairs of the object can be accessed by looping over the object's keys and accessing the value associated with each particular key. With Object.entries(), the key-value pairs of the object are returned as an array of two-element arrays, which can then be looped over to access the key-value pairs. Both of these approaches are useful for looping through an object's key-value pairs and printing out the corresponding values.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe