-3

Javascript Array push issue

I have a object:

people: [{name: peter, age: 27, email:'peter@abc.com'}]

I want to push:

people.push({
        name: 'John',
        age: 13,
        email: 'john@abc.com'
});
people.push({
        name: 'peter',
        age: 36,
        email: 'peter@abc.com'
});

The finally I want is:

people: [
{name: 'peter', age: 36, email:'peter@abc.com'},
{name: 'john', age: 13, email:'john@abc.com'},
]

I dont have any key but the email is a unique

Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66
kenny
  • 221
  • 2
  • 4
  • 13

2 Answers2

2

You can also do like this by generating an Array method. It takes two arguments. First one designates the object to push and the second is the unique property to check to replace if a previously inserted item exists.

var people = [{name: 'peter', age: 27, email:'peter@abc.com'}];
Array.prototype.pushWithReplace = function(o,k){
 var fi = this.findIndex(f => f[k] === o[k]);
 fi != -1 ? this.splice(fi,1,o) : this.push(o);
 return this;
};
people.pushWithReplace({name: 'John', age: 13, email: 'john@abc.com'}, "email");
people.pushWithReplace({name: 'peter', age: 36, email: 'peter@abc.com'},"email");
console.log(people);
Redu
  • 25,060
  • 6
  • 56
  • 76
1

There is no "update" method as is in JavaScript.

What you have to do, is simply looping through your array first to check if the object is already inside.

function AddOrUpdatePeople(people, person){
    for(var i = 0; i< people.length; i++){
        if (people[i].email == person.email){
            people[i].name = person.name;
            people[i].age = person.age;
            return;                          //entry found, let's leave the function now
        }
    }
    people.push(person);                     //entry not found, lets append the person at the end of the array.
}
Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66