Skip to content

Update array of objects JavaScript | Example code

  • by

Use findIndex() method to get index of the object and then use bracket notation to Update array of objects JavaScript.

Update array of objects JavaScript

Simple example code with steps:-

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

Change name where id is 2.

<!DOCTYPE html>
<html>
<body>

  <script>

   let myArray = [
   {id: 0, name: "Jhon"},
   {id: 1, name: "Sara"},
   {id: 2, name: "Domnic"},
   {id: 3, name: "Bravo"}
   ],

    //Find index of specific object using findIndex method.    
    objIndex = myArray.findIndex((obj => obj.id == 1));

   //Update object's name property.
   myArray[objIndex].name = "Laila"

   console.log(myArray)
 </script>

</body>
</html> 

Output:

Update array of objects JavaScript

How to update values of every object in an array JavaScript?

Answer: Use map function with arrow function. 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"
  }
]

Source: stackoverflow.com/

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. Required fields are marked *

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