Borislav Hadzhiev
Sun Oct 10 2021·3 min read
Photo by George Stackpole
To change the value of an object in an array:
findIndex()
method to get the index of the specific object.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
.
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
.
map
method.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.
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.