How to use foreach with key value pairs - JavaScript

Mo Ibra

Mo Ibra

Jan 5, 2023

In this article we will learn how to use forEach with key value pairs in JavaScript.

It is very common to use forEach with key value pairs in JavaScript in JavaScript.


Problem

Now we have a problem which is that we want to use forEach with key value pairs.

Now let's imagine that we have an array with a set of numbers like this:

const array = [1, 2, 3, 4, 5, 6];

We want to use forEach with both the value and the index.

How to solve this problem?

JavaScript's forEach() function takes a callback as a parameter, We can calls the callback with the value as the first parameter and the array index as the 2nd parameter.


Use forEach with key value pairs

As we said before, we can calls the callback with value and index.

Let's see an example

const array = [1, 2, 3, 4, 5];

array.forEach((value, index) => {
    console.log("Index:", index, "Value:", value);
});

Output

Index: 0 Value: 1
Index: 1 Value: 2
Index: 2 Value: 3
Index: 3 Value: 4
Index: 4 Value: 5

Use forEach with key value pairs in Objects.

We can use forEach with objects as well.

Example

// Object
const object = {
    name: 'John Doe',
    age: 30,
    country: "USA"
};

// Use `forEach` to itrate over object
Object.keys(object).forEach(key => {
    console.log(key, object[key]);
});

Output

name John Doe
age 30     
country USA

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: