r/JavaScriptTips • • Apr 30 '23

How to Iterate Object Key Value in JavaScript?

The simplest and most straightforward way to iterate over an object's key-value pairs is to use a for...in loop. This loop is designed specifically for iterating over the properties of an object, and it works by iterating over all the keys in the object and executing a block of code for each key. Here's an example:

 const myObject = {a: 1, b: 2, c: 3};

for (const key in myObject) {
  console.log(`${key}: ${myObject[key]}`);
}

In this example, we define an object called myObject with three properties: a, b, and c. We then use a for...in loop to iterate over each key in the object, and for each key, we log the key-value pair to the console.

Another way to iterate over an object's key-value pairs is to use the Object.keys() method to get an array of all the keys in the object, and then use a for...of loop to iterate over the array. Here's an example:

const myObject = {a: 1, b: 2, c: 3};

for (const key of Object.keys(myObject)) {
  console.log(`${key}: ${myObject[key]}`);
}

In this example, we use the Object.keys() method to get an array of all the keys in the myObject object. We then use a for...of loop to iterate over the array of keys, and for each key, we log the key-value pair to the console.

In conclusion, iterating over object key-value pairs is a common task in JavaScript programming, and there are several ways to achieve it. The for...in loop, Object.keys() method with for...of loop, and Object.entries() method with for...of loop are all great options to choose from depending on your use case.

6 Upvotes

0 comments sorted by