Use the findIndex() method to get an index of the object and then use bracket notation to Update the 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 a 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:
Or you can use various techniques depending on your specific requirements. Here are a few common approaches:
Using the map()
method:
const newArray = originalArray.map((obj) => {
if (/* condition to identify the object to be updated */) {
// Perform updates on the object properties
return { ...obj, /* updated properties */ };
}
// Return the object as-is if no updates are needed
return obj;
});
Using the forEach()
method:
originalArray.forEach((obj) => {
if (/* condition to identify the object to be updated */) {
// Perform updates on the object properties
Object.assign(obj, /* updated properties */);
}
});
How to update the values of every object in an array of JavaScript?
Answer: Use the map function with the 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/
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