Categories
JavaScript Answers

How to Loop Through a JavaScript Associative Array Object?

Spread the love

Sometimes, we want to loop through a JavaScript associative array object in our JavaScript code.

In this article, we’ll look at how to loop through a JavaScript associative array object.

Use the for-in Loop

One way to loop through a JavaScript associative array object with the for-in loop.

For instance, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
}
for (const key in obj) {
  const value = obj[key];
  console.log(key, value);
}

We create an obj object with some key-value pairs.

Then we loop through the object keys with the for-in loop.

We get the property value with obj[key] in the loop body.

Therefore, from the console log, we get:

a 1
b 2
c 3

Use the Object.entries with the forEach Method

We can use the Object.entries method to return an array of key-value pair arrays.

Then we can use the forEach method to loop through the array.

For instance, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
}
Object.entries(obj).forEach(([key, value]) => console.log(key, value));

We call forEach with a callback with an array with the key and value destructured from it.

Then in the callback body, we log the key and value .

Therefore, we get the same result as before.

Use the for-of Loop

Another way to loop through the key-value pairs is to use the for-of loop.

For example, we can write:

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

for (const [key, value] of Object.entries(obj)) {
  console.log(key, value)
}

We use Object.entries to return an array of key-value pair arrays.

And we destructure the key and value from the destructured key-value arrays.

And we log the key and value from the console log.

Conclusion

There’re several ways we can use to loop through the key-value pair of an associative array object with JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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