0

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.

  • Any help is appreciated!

const lastname = 'Jackson';
const id = 2;

const persons = [
    {
        id: 1
        firstname: 'Mary',
        lastname: 'Jackson'
    },

    {
        id: 2
        firstname: 'Ash'
    }
]

3 Answers 3

2

Here's a one-liner to update it without mutating the original array:

const updatedPersons = persons.map(p => p.id === id ? {...p, lastname} : p);
Sign up to request clarification or add additional context in comments.

Comments

1
persons.forEach(person => {
    if(this.id === person.id) person.lastname = this.lastname
})

Comments

1

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;
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.