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

avatar

Borislav Hadzhiev

Sun Oct 10 20212 min read

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

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

  1. Call the forEach() method, passing it a function.
  2. The function will get called with each object in the array to which you can add the key/value pair.
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 pass to the Array.forEach method will get executed once for each element in the array.

The array element gets passed to the function on each iteration, to which we can directly add the key value/pair.

An alternative, but very common approach is to use the map method to create a new array containing the existing and additional key/value pairs.

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 for each element in the array.

Notice that we use the spread operator (...).

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 transfer over our id property and add a color property on each object.

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

The patter when using the forEach method is to mutate (change) some object or array.

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

For this reason, most experienced developers avoid using too many mutations on the same array / object.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee