Change a Value of an Object in an Array in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 10 20212 min read

Change a Value of an Object in an Array #

To change the value of an object in an array:

  1. Call the findIndex() method to get the index of the specific object.
  2. Access the array at the index and change the property's value using dot notation.
index.js
const arr = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, ]; const index = arr.findIndex(object => { return object.id === 2; }); // ๐Ÿ‘‰๏ธ 1 if (index !== -1) { arr[index].name = 'John'; } // ๐Ÿ‘‡๏ธ [{id: 1, name: 'Alice'}, {id: 2, name: 'John'}] console.log(arr);

The function we pass to the Array.findIndex method gets called with each object in the array until it returns a truthy value or iterates over the entire array.

If the function never returns a truthy value, the findIndex method returns -1, otherwise it returns the index of the array element.

We want to be sure that an object with the supplied id is found, therefore we conditionally check that the index returned from the findIndex method is not equal to -1.

Indexes are zero-based in JavaScript, therefore the first element in the array has an index of 0 and the last element an index of arr.length - 1.

After we get the index of the object, we can use dot notation to change the value of a specific property in the object.

In the example we access the object at index 1 and change the value associated to its name property to John.

Most experienced developers avoid changing (mutating) objects and arrays in place, instead they create a new array containing the desired values. We can achieve this using the map method.
index.js
const arr = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, ]; const newArr = arr.map(object => { if (object.id === 2) { // ๐Ÿ‘‡๏ธ change value of name property return {...object, name: 'John'}; } return object; }); // ๐Ÿ‘‡๏ธ [{id: 1, name: 'Alice'}, {id: 2, name: 'John'}] console.log(newArr); // ๐Ÿ‘‡๏ธ [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}] console.log(arr);

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

Inside the function we use the spread operator (...) to create a copy of the object and change the value of the name property.

There are multiple differences between this and the previous approach, the main one being, we don't change the contents of the original array, instead we get a new array, containing the updated value.

Another difference is that if there were multiple object with an id of 2 in our array, using the map method we would have changed the value of the name property of all of them.

The findIndex method only finds the index of the first array element that matches a condition, even if we had multiple objects with id of 2, only the index of the first match would be returned.

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