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.
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.
xxxxxxxxxx
1
const users = [
2
{ id: 1, name: 'Tom' },
3
{ id: 2, name: 'Ann' },
4
{ id: 3, name: 'Mark' },
5
];
6
7
const index = users.findIndex((user) => user.name === 'Ann');
8
9
users[index].name = 'Kate';
10
11
console.log(JSON.stringify(users[index], null, 4));
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
.
xxxxxxxxxx
1
const users = [
2
{ id: 1, name: 'Tom' },
3
{ id: 2, name: 'Ann' },
4
{ id: 3, name: 'Mark' },
5
];
6
7
const replacement = { id: 2, name: 'Kate' };
8
9
const index = users.findIndex((user) => user.name === 'Ann');
10
11
users[index] = replacement;
12
13
console.log(JSON.stringify(users[index], null, 4));