2016-06-20 52 views
-4

JavaScript數組推動問題JavaScript數組添加或更新

我有一個目標:

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

我要推:

people.push({ 
     name: 'John', 
     age: 13, 
     email: '[email protected]' 
}); 
people.push({ 
     name: 'peter', 
     age: 36, 
     email: '[email protected]' 
}); 

的最後我想要的是:

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

我沒有任何鑰匙,但電子郵件l是唯一的

+1

有什麼問題?重複的條目? –

+0

一切看起來是正確的,除了在結果數組中的尾隨逗號 –

+1

http://stackoverflow.com/help/how-to-ask – dabadaba

回答

1

在JavaScript中沒有「更新」方法。

你必須做的,只是簡單地循環你的數組,以檢查對象是否已經在裏面。

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

你也可以通過生成一個Array方法來做到這一點。它有兩個參數。第一個指定要推送的對象,第二個指定要檢查的獨特屬性,以替換之前插入的項目是否存在。

var people = [{name: 'peter', age: 27, email:'[email protected]'}]; 
 
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: '[email protected]'}, "email"); 
 
people.pushWithReplace({name: 'peter', age: 36, email: '[email protected]'},"email"); 
 
console.log(people);