Cho Keung Yuen Cho Keung Yuen - 1 year ago 139
Javascript Question

Javascript Array push and update

Javascript Array push issue

I have a object:

people: [{name: peter, age: 27, email:''}]

I want to push:

name: 'John',
age: 13,
email: ''
name: 'peter',
age: 36,
email: ''

The finally I want is:

people: [
{name: 'peter', age: 36, email:''},
{name: 'john', age: 13, email:''},

I dont have any key but the email is a unique

Answer Source

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 =={
            people[i].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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download