Cho Keung Yuen Cho Keung Yuen - 5 months ago 9
Javascript Question

Javascript Array push and update

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

Answer

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.
}
Comments