Reputation: 445
How can I add a value to an object in the array persons
?
The value I want to add is lastname
and variable id
is the id of the object the value should be added to.
const lastname = 'Jackson';
const id = 2;
const persons = [
{
id: 1
firstname: 'Mary',
lastname: 'Jackson'
},
{
id: 2
firstname: 'Ash'
}
]
Upvotes: 0
Views: 134
Reputation: 331
Here's a one-liner to update it without mutating the original array:
const updatedPersons = persons.map(p => p.id === id ? {...p, lastname} : p);
Upvotes: 2
Reputation: 1082
You need to loop over the array and add a condition to check if id matches person.id
then add lastname
to that person object. If you don't want to change the original array go for .map()
else .forEach()
With .forEach()
:
persons.forEach(person => {
if (person.id === id) {
person.lastname = lastname
}
})
With .map()
:
const newPersonsArr = persons.map(person => {
if (person.id === id) {
return {
...person,
lastname
}
}
return person;
})
Upvotes: 1
Reputation:
persons.forEach(person => {
if(this.id === person.id) person.lastname = this.lastname
})
Upvotes: 1