How to Add a Key-Value Pair to All Objects in an Array in JavaScript
A common data transformation task in JavaScript is to enrich an array of objects by adding a new property to every object in the collection. You might need to add a default status to a list of tasks, add a country to a list of users, or tag each item with a specific flag.
This guide will teach you the two primary approaches for this task. You will learn the mutating method using forEach(), which modifies the original array, and the immutable method using map(), which creates a new array with the updated objects. Understanding the difference is crucial for writing predictable and maintainable code.
The Goal: Adding a Property to Each Object
Imagine you have an array of simple objects, and you want to add a color: 'red' property to each one.
Starting Array:
const items = [
{ id: 1, name: 'apple' },
{ id: 2, name: 'banana' }
];
Desired Result:
[
{ id: 1, name: 'apple', color: 'red' },
{ id: 2, name: 'banana', color: 'red' }
]
Method 1 (Immutable - Recommended): Using Array.prototype.map()
The map() method is the standard and recommended best practice for this task because it is immutable. It does not change the original array. Instead, it creates and returns a new array containing the modified objects.
The logic:
- Use the
map()method to iterate over the source array. - In each iteration, create a new object.
- Use the spread syntax (
...) to copy all properties from the original object into the new one. - Add your new key-value pair to the new object.
- Return the new object from the callback function.
The solution:
const items = [
{ id: 1, name: 'apple' },
{ id: 2, name: 'banana' }
];
const updatedItems = items.map(item => {
// Create a new object with all the properties of the original
// and add the new 'color' property.
return { ...item, color: 'red' };
});
// The new array contains the updated objects
console.log(updatedItems);
// Output: [ { id: 1, name: 'apple', color: 'red' }, { id: 2, name: 'banana', color: 'red' } ]
// The original array is unchanged
console.log(items);
// Output: [ { id: 1, name: 'apple' }, { id: 2, name: 'banana' } ]
Output:
[ { id: 1, name: 'apple', color: 'red' }, { id: 2, name: 'banana', color: 'red' } ]
[ { id: 1, name: 'apple' }, { id: 2, name: 'banana' } ]
Method 2 (Mutating): Using Array.prototype.forEach()
The forEach() method iterates over each element in an array and allows you to perform an action. This method mutates (modifies) the original array in place.
The problem:
- This approach can lead to unexpected side effects if other parts of your application are still using the original array.
The solution:
const items = [
{ id: 1, name: 'apple' },
{ id: 2, name: 'banana' }
];
// forEach modifies each object directly in the original array.
items.forEach(item => {
item.color = 'red';
});
// The original array has been changed.
console.log(items);
// Output: [ { id: 1, name: 'apple', color: 'red' }, { id: 2, name: 'banana', color: 'red' } ]
While this works and can be slightly faster, the map() method is generally safer and leads to more predictable code.
Adding a Key with a Dynamic or Special Name
If the key you need to add contains spaces, hyphens, or is stored in a variable, you must use bracket notation [] instead of dot notation.
The problem:
- You need to add a key named
"full-name".
The solution:
const items = [{ id: 1 }, { id: 2 }];
// Using forEach (mutating)
items.forEach(item => {
item['full-name'] = 'Tom Nolan';
});
// Using map (immutable)
const newItems = items.map(item => {
const keyName = 'full-name';
return { ...item, [keyName]: 'Tom Nolan' };
});
Adding a Property Conditionally
You can easily add a property with a value that depends on the other properties of the object.
The logic:
- Inside your
map()orforEach()callback, use anifstatement or a ternary operator to determine the value of the new property.
The following example adds a status property, setting it to "Complete" for even IDs and "Pending" for odd IDs.
const tasks = [{ id: 1 }, { id: 2 }, { id: 3 }];
const tasksWithStatus = tasks.map(task => {
const newStatus = (task.id % 2 === 0) ? 'Complete' : 'Pending';
return { ...task, status: newStatus };
});
console.log(tasksWithStatus);
Output:
[
{ id: 1, status: 'Pending' },
{ id: 2, status: 'Complete' },
{ id: 3, status: 'Pending' }
]
Conclusion
Adding a key-value pair to all objects in an array is a common data transformation that can be handled in two main ways.
- The
map()method is the recommended best practice. It follows the principles of immutability by creating a new array, which makes your code safer and more predictable. Use it with the spread syntax (...) to create new objects. - The
forEach()method is a valid alternative that mutates the original array. It can be slightly faster but may lead to unintended side effects.
For modern, functional JavaScript, always prefer the immutable map() approach.