How to Use forEach() with Key Value Pairs

Jul 14, 2021

JavaScript's forEach() function takes a callback as a parameter, and calls that callback for each element of the array. It calls the callback with the value as the first parameter and the array index as the 2nd parameter.

// Prints "0: a, 1: b, 2: c"
['a', 'b', 'c'].forEach(function callback(value, index) {
  console.log(`${index}: ${value}`);
});

forEach() is a method on JavaScript arrays, not objects. To iterate over an object, you must turn it into an array using Object.entries(), Object.keys(), or Object.values(). After that, you can then use forEach() to iterate through the keys, values, or entries:

const obj = {
  name: 'Jean-Luc Picard',
  rank: 'Captain'
};

// Prints "name Jean-Luc Picard" followed by "rank Captain"
Object.keys(obj).forEach(key => {
  console.log(key, obj[key]);
});
const obj = {
  name: 'Jean-Luc Picard',
  rank: 'Captain'
};

// Prints "Jean-Luc Picard" followed by "Captain"
Object.values(obj).forEach(val => {
  console.log(val);
});
const obj = {
  name: 'Jean-Luc Picard',
  rank: 'Captain'
};

// Prints "name Jean-Luc Picard" followed by "rank Captain"
Object.entries(obj).forEach(entry => {
  const [key, value] = entry;
  console.log(key, value);
});

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials