Update Object in array JavaScript | Example code

  • by

Use the map() function or findIndex() function to update Object in array JavaScript. Both methods are built-in array method is provided by JavaScript.

Array.prototype.map(element => $updateCondition);
Array.prototype.map($callbackFn);
Array.prototype.findIndex(element => $condition);
Array.prototype.findIndex($callbackFn);

Update Object in array JavaScript

Simple example code update an Object’s Property in Array of Objects.

Using map() function

This method iterates over the array. On each iteration, check if the current object is the one to be updated.

<!DOCTYPE html>
<html>
<body>

  <script>

    const osArray = [
    {id: 0, name: "Windows"},
    {id: 1, name: "Linux"},
    {id: 2, name: "MacOS"},
    ];
    
    const updatedOSArray = osArray.map(p =>p.id === 1
      ? { ...p, name: 'Ubuntu' }
      : p
      );

    console.log(updatedOSArray);

  </script>

</body>
</html> 

Output:

Update Object in array JavaScript

Using findIndex function

Find the index of the object using findIndex method. Store the index as a variable. Do a simple update like this: yourArray[indexThatyouFind].

<script>

    let myArray = [
    {id: 0, name: "Jhon"},
    {id: 1, name: "Sara"},
    {id: 2, name: "Domnic"},
    {id: 3, name: "Bravo"}
    ],
    
    objIndex = myArray.findIndex((obj => obj.id == 1));
    myArray[objIndex].name = "Laila"

    console.log(myArray[objIndex])

</script>

Output: Object { id: 1, name: “Laila” }

How to update values of every object in an array of objects in Javascript?

Answer: Update a value of car in all objects in an array(data) with the values from newData. Just take the index of the object being iterated over, and look it up in the newData array.

const data = [
  { id: 1, car: "Toyota 2020", owner: "BM" },
  { id: 2, car: "Nissan", owner: "DK" },
  { id: 3, car: "Mazda", owner: "JA" },
  { id: 4, car: "Ford", owner: "DS" }
];
const newData = ["Audi", "Bentley", "BMW", "Buick"];

const newCars = data.map((obj, i) => ({ ...obj, car: newData[i] }));
console.log(newCars);

Output:

[
  {
    "id": 1,
    "car": "Audi",
    "owner": "BM"
  },
  {
    "id": 2,
    "car": "Bentley",
    "owner": "DK"
  },
  {
    "id": 3,
    "car": "BMW",
    "owner": "JA"
  },
  {
    "id": 4,
    "car": "Buick",
    "owner": "DS"
  }
]

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.