George Bleasdale
George Bleasdale

Reputation: 351

Find and replace a matching object in an array - JavaScript

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

Upvotes: 3

Views: 7583

Answers (3)

iliya.rudberg
iliya.rudberg

Reputation: 789

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

Upvotes: 1

Rafael Lucini
Rafael Lucini

Reputation: 599

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

Upvotes: 8

Testor10
Testor10

Reputation: 60

You can use "find" method from Lodash library (https://lodash.com/docs/4.17.11#find).

You search for the person you want and, with the index, you can easily change it.

Upvotes: 0

Related Questions