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

avatar
Borislav Hadzhiev

Last updated: Mar 1, 2024
5 min

banner

# Table of Contents

  1. Add a Key/Value pair to all Objects in Array in JavaScript
  2. Add a Key/Value pair to all Objects in Array using Array.map()
  3. Using Object.assign() instead of the spread syntax (...)
  4. Conditionally adding a key-value pair to all objects in an array
  5. Add a Key/Value pair to all Objects in an Array using for...of
  6. Add a Key/Value pair to all Objects in an Array using a for loop

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

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

  1. Use the Array.forEach() method to iterate over the array.
  2. Use dot notation to add a key/value pair to each 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);

add key value pair to all objects in array

The code for this article is available on GitHub

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.

If the name of the key you need to add to the object contains hyphens, spaces or starts with a number, use bracket notation to add the key to each object.

index.js
const arr = [{id: 1}, {id: 2}]; arr.forEach(object => { object['full name'] = 'Bobby Hadz'; }); // [ // { id: 1, 'full name': 'Bobby Hadz' }, // { id: 2, 'full name': 'Bobby Hadz' } // ] console.log(arr);

The Array.forEach() method iterates over the array and adds the key-value pair to each object in place.

If you'd rather not mutate the original array, use the Array.map() method.

# Add a Key/Value pair to all Objects in Array using Array.map()

This is a three-step process:

  1. Use the Array.map() method to iterate over the array.
  2. Use the spread syntax to add a key/value pair to each 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);

add key value pair to all objects in array using array map

The code for this article is available on GitHub

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

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

index.js
const arrWithColor = arr.map(object => { return {...object, color: 'red'}; });
An easy way to think about the spread syntax is that we are unpacking the key/value pairs of a source object into a target object.

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

The Array.map() method is different than Array.forEach() because map() returns a new array, whereas forEach() returns undefined.

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

# Using Object.assign() instead of the spread syntax (...)

You can also use the Object.assign() method instead of using the spread syntax.

index.js
const arr = [{id: 1}, {id: 2}]; const arrWithColor = arr.map(object => { return Object.assign(object, {color: 'red', country: 'Chile'}); }); // [ // { id: 1, color: 'red', country: 'Chile' }, // { id: 2, color: 'red', country: 'Chile' } // ] console.log(arrWithColor);

using object assign instead of the spread syntax

The code for this article is available on GitHub

We used the Object.assign() method to copy the key-value pairs of one or more objects into a target object.

The arguments we passed to the Object.assign() method are:

  1. the target object - the object to which the provided properties will be applied.
  2. the source object(s) - one or more objects that contain the properties we want to apply to the target object.

You can imagine that the key-value pairs of the object we passed as the second argument to Object.assign(), get copied into the object we supplied for the first argument.

# Conditionally adding a key-value pair to all objects in an array

If you need to conditionally add a key-value pair to all objects in an array, use the ternary operator.

index.js
const arr = [{id: 1}, {id: 2}]; const arrWithColor = arr.map(object => { return {...object, name: object.id > 1 ? 'Bobby' : 'Alice'}; }); // ๐Ÿ‘‡๏ธ [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bobby' } ] console.log(arrWithColor);

conditionally adding key value pair to all objects in array

The ternary operator is very similar to an if/else statement.

If the expression to the left of the question mark returns a truthy value, the operator returns the value to the left of the colon, otherwise, the value to the right of the colon is returned.

In the example, we check if the current object's id property is greater than 1.

If the condition is met, the string Bobby is returned for the name property, otherwise, the string Alice is returned.

Here is the equivalent if/else statement.

index.js
const arr = [{id: 1}, {id: 2}]; const arrWithColor = arr.map(object => { if (object.id > 1) { return {...object, name: 'Bobby'}; } else { return {...object, name: 'Alice'}; } }); // ๐Ÿ‘‡๏ธ [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bobby' } ] console.log(arrWithColor);
The code for this article is available on GitHub

If the object's id property is greater than 1, the if block runs, otherwise, the else block runs.

# Add a Key/Value pair to all Objects in an Array using for...of

You can also use a simple for...of loop to add a key-value pair to all objects in an array.

index.js
const arr = [{id: 1}, {id: 2}]; for (const obj of arr) { obj.color = 'red'; } // ๐Ÿ‘‡๏ธ [ { id: 1, color: 'red' }, { id: 2, color: 'red' } ] console.log(arr);

The for...of statement is used to loop over iterable objects like arrays, strings, Map, Set and NodeList objects and generators.

On each iteration, we add a new key-value pair to the current object, in place.

# Add a Key/Value pair to all Objects in an Array using a for loop

You can also use a basic for loop to add a key-value pair to all objects in an array.

index.js
const arr = [{id: 1}, {id: 2}]; for (let index = 0; index < arr.length; index++) { arr[index].color = 'green'; } // ๐Ÿ‘‡๏ธ [ { id: 1, color: 'green' }, { id: 2, color: 'green' } ] console.log(arr);

The basic for loop is quite verbose in comparison to forEach() or for...of.

We also have to use the index to access the object of the current iteration before adding a key-value pair.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev