Find and replace a matching object in an array - JavaScript

Viewed 6553

I have an array of people objects. When a new person is added, a function should check if someone with that name has already been added. If so, that object should be replaced with the new one. If the new person hasn't already been added then they are simply added to the end. What's the best way to do that?

Here's the object

    const people = [
    {name: Joe M, town: London},
    {name: Julie A, town: London},
    {name: Sally N, town: Edinburgh},
    {name: Max M, town: Liverpool}
  ]

Here's what I tried

  for(let key in people) {
  if(people[key].name === newPerson.name){
    people.splice(key, 1, newPerson)
  } else {
    this.people.push(this.newPerson)
  }
}
3 Answers

There are many ways, try this:

  const index = people.findIndex(p => p.name === newPerson.name)

  if(index === -1) {
     people.push(newPerson);
  } else {
     people[index] = newPerson;
  }

Using lodash, you can find mathcing index, if user will not found indexOf will return -1, so we can check this and do like this:

const index = _.indexOf(people, { name: newPerson.name});
if (index >= 0) people.splice(index, 1, newPerson)
else people.push(newPerson)

Also, if you dont wont to use lodash you can replace index constant with: people.findIndex(i => i.name === newPerson.name);

Related