Javascript阵列推送问题
我有一个对象:
people: [{name: peter, age: 27, email:'peter@abc.com'}]
我想推动:
people.push({
name: 'John',
age: 13,
email: 'john@abc.com'
});
people.push({
name: 'peter',
age: 36,
email: 'peter@abc.com'
});
我最终想要的是:
people: [
{name: 'peter', age: 36, email:'peter@abc.com'},
{name: 'john', age: 13, email:'john@abc.com'},
]
我没有任何密钥,但电子邮件是唯一的
答案 0 :(得分: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 :(得分:1)
您也可以通过生成Array方法来执行此操作。它需要两个参数。第一个指定要推送的对象,第二个是要检查以替换先前插入的项目的唯一属性。
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);