How do I loop through a JavaScript associative array object? | by John Au-Yeung | June 2022

0
Photo by Austin Distel on Unsplash

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

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

A way to iterate over a JavaScript associative array object with the for-in loop.

For example, 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 a obj object with key-value pairs.

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

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

Therefore, from the console log we get:

a 1
b 2
c 3

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

Then we can use the forEach method to iterate over the array.

For example, 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 reminder with an array with the key and value unstructured from it.

Then in the body of the callback we register the key and value .

Therefore, we get the same result as before.

Another way to iterate over 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 arrays of key-value pairs.

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

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

There are several ways to iterate over the key-value pair of an associative array object with JavaScript.

More content on PlainEnglish.io. Subscribe to our free weekly newsletter. follow us on Twitter and LinkedIn. Discover our Community Discord and join our Talent Collective.

Share.

About Author

Comments are closed.