Use findIndex() method to find objects in Array by value and use bracket notation to update objects in JavaScript.
- Find the index of the object using
findIndex
method. - Store the index as variables.
- Do a simple update like this:
yourArray[indexThatyouFind]
myArray[objIndex].name = "value"
JavaScript find the object in the array by property value and update
Simple example code update object where id is 1.
<!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));
//Log object to Console.
console.log("Before update: ", myArray[objIndex])
//Update object's name property.
myArray[objIndex].name = "Laila"
//Log object to console again.
console.log("After update: ", myArray[objIndex])
</script>
</body>
</html>
Output:
Or use the Array.find()
method along with the Object.hasOwnProperty()
method.
const users = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 }
];
// Let's find the user with id 2 and update their age
const userToUpdate = users.find(user => user.hasOwnProperty('id') && user.id === 2);
if (userToUpdate) {
userToUpdate.age = 32;
}
console.log(users);
How can I find and update values in an array of objects?
Answer: You can use findIndex() to find the index in the array of the object and replace it as required:
var item = {...}
var items = [{id:2}, {id:2}, {id:2}];
var foundIndex = items.findIndex(x => x.id == item.id);
items[foundIndex] = item;
This assumes unique IDs. If your IDs are duplicated (as in your example), it’s probably better if you use forEach:
items.forEach((element, index) => {
if(element.id === item.id) {
items[index] = item;
}
});
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