Update Object in Array Without Mutation in Javascript

3 min read

In this article, we are going to learn how to update an object property inside an array in javascript.

We will be using javascript higher order map method, that returns a new array, which means we are not mutating the original array (data).

To use the logic anywhere in app I turned it into a function, that takes 3 parameters.

  1. The list (array) we want to update
  2. id of the object we want to update
  3. updated data (object)
function update(arr, id, updatedData) {
return arr.map((item) =>
item.id === id ? { ...item, ...updatedData } : item
)
}
const arr = [
{ id: '01', name: 'John', email: 'john@email.com' },
{ id: '02', name: 'Sara', email: 'sara@email.com' },
{ id: '03', name: 'Michael', email: 'michael@email.com' },
]
const id = '01'
const updatedData = { email: 'john1@email.com' }
const result = update(arr, id, updatedData)
console.log(result)

This function can be used to update any kind of UI in javascript or javascript related framework, like React, Vue, Angular, etc.

Let's break down the answer into pieces.

1. Loop through Array via map method

According to MDN docs:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

map method takes callback in which we are writing a condition item.id === id if this condition is fulfilled, return and update only that object, and leave the rest of the elements of an array as it is.

2. Updating object using Spread Operator

For updating object, we are using javascript spread operator. We say, keep the old data, and add the updated data to old data {...item, ...updatedData}

That’s all!

Do you wonder why old email is replaced by new email?

Can Javascript Object have duplicate keys?

No, this is how the javascript object works, it can’t have duplicate keys (keys with the same name), it will override old values with the latest one.

Example

const obj = {
id: '01',
name: 'John',
id: '02',
}
console.log(obj) // output: {id: '02', name: 'John'}

Last but not least,

Let's verify if our original array is mutated or not just by console.log the array after result.

....
const arr = [
{ id: '01', name: 'John', email: 'john@email.com' },
{ id: '02', name: 'Sara', email: 'sara@email.com' },
{ id: '03', name: 'Michael', email: 'michael@email.com' },
]
const id = '01'
const updatedData = { email: 'john1@email.com' }
const result = update(arr, id, updatedData)
console.log('result', result)
console.log('original array', arr)

Output

update array of object without mutation

If we check the console we can see our original array data is not mutated and same as it was before.

If you have learned something new from this article, feel free to share it with your friends.