Add a Key/Value pair to all Objects in Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Add a Key/Value pair to all Objects in Array #

To add a key/value pair to all objects in an array:

  1. Use the Array.forEach() method to iterate over the array.
  2. On each iteration, use dot notation to add a key/value pair to the current object.
  3. The key/value pair will get added to all objects in the array.
index.js
const arr = [{id: 1}, {id: 2}]; arr.forEach(object => { object.color = 'red'; }); // 👇️ [{id: 1, color: 'red'}, {id: 2, color: 'red'}] console.log(arr);

The function we passed to the Array.forEach method gets called with each element (object) in the array.

On each iteration, we add a key/value pair to the current object.

Alternatively, you can use the map() method.

To add a key/value pair to all objects in an array:

  1. Use the Array.map() method to iterate over the array.
  2. On each iteration, use the spread syntax to add the key/value pair to the current object.
  3. The key/value pair will get added to all objects in the new array.
index.js
const arr = [{id: 1}, {id: 2}]; const arrWithColor = arr.map(object => { return {...object, color: 'red'}; }); // 👇️ [{id: 1, color: 'red'}, {id: 2, color: 'red'}] console.log(arrWithColor); // 👇️ [{id: 1}, {id: 2}] console.log(arr);

The function we passed to the Array.map method gets called with each element (object) in the array.

We used the spread operator (...) to unpack the key/value pairs of each object and added an additional key/value pair.

An easy way to think about the ... operator is - we are unpacking the key/value pairs of a source array into a target array.

We basically transfer over the id property and add a color property to each object.

map is different than forEach because map returns a new array, whereas forEach returns undefined.

When using the forEach() method, we mutate the array in place.

Mutating objects and arrays can be difficult to reason about, especially in larger code bases.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.