1. 1
    3 Ways to Update the Content of an Array of Objects with Javascript
    1m 43s
⚠️ This lesson is retired and might contain outdated information.

3 Ways to Update the Content of an Array of Objects with Javascript

Share this video with your friends

Social Share Links

Send Tweet

Javascript offers different ways to manipulate an array. One of this situations is the need of update or modify the content of one of the items of an array of objects. To do this we can use mutable methods like index access or immutable ways by using Array.map or a combination of Array.findIndex and Array.slice

Matias Hernandez: [0:00] JavaScript allow us to update the content of our object of arrays. To do this, we will use this little handy function that creates random user objects. One method to update the content of the array objects is accessing the elements of it by the array index, but this is a mutable method.

[0:24] There are immutable ways to do the same goal, like the map of function. Map iterates over the array and by using a callback function allow access to the items. Map creates a new array with the content return it by the cover function.

[0:39] In this case, we use a conditional block to update only the item that have an ID equal to three. By using object of spread syntax, we update only the property name. In case that the conditional block is false, we return the original item.

[1:00] Another way to update the content of one of the items by not knowing the index is by using the findIndex function. To avoid mutate the original array, we will use arrays slice function as our helper, findIndex allow us to use a test function. We'll return the index of the element that passed the test.

[1:21] Then, after we got the index, we can create a new item by using object of spread syntax to update only the name property following by creating a new array using array slice to get two portions of the array, before and after the index. In summary, JavaScript offers different ways in a mutable and immutable fashion to update and narrow your object.