EN
JavaScript - change value of object inside array
0
points
In this article, we would like to show you how to change the value of an object inside an array using JavaScript.
1. Change single property
In this example, we use findIndex()
method to get the index
of the object we want to change. Then using bracket notation we change the value of the object's name
property.
// ONLINE-RUNNER:browser;
const users = [
{ id: 1, name: 'Tom' },
{ id: 2, name: 'Ann' },
{ id: 3, name: 'Mark' },
];
const index = users.findIndex((user) => user.name === 'Ann');
users[index].name = 'Kate';
console.log(JSON.stringify(users[index], null, 4));
2. Change whole object
In this example, we use findIndex()
method to get the index
of the object we want to change. Then using bracket notation we change the whole object in users
array to the replacement
.
// ONLINE-RUNNER:browser;
const users = [
{ id: 1, name: 'Tom' },
{ id: 2, name: 'Ann' },
{ id: 3, name: 'Mark' },
];
const replacement = { id: 2, name: 'Kate' };
const index = users.findIndex((user) => user.name === 'Ann');
users[index] = replacement;
console.log(JSON.stringify(users[index], null, 4));