在javascript中向对象数组中添加或替换
如何向现有对象数组中添加或替换对象。假设我有这样的现有阵列:在javascript中向对象数组中添加或替换,javascript,Javascript,如何向现有对象数组中添加或替换对象。假设我有这样的现有阵列: productOffer.view = [ {id: 1, name: "john"}, {id: 2, name: "Sam"} ] productOffer.view.forEach(function(el,i){ if(el.id == productOffer.createId){ productOffer.view[i] = ajaxCall.responseJSON } else
productOffer.view = [
{id: 1, name: "john"},
{id: 2, name: "Sam"}
]
productOffer.view.forEach(function(el,i){
if(el.id == productOffer.createId){
productOffer.view[i] = ajaxCall.responseJSON
} else {
productOffer.view.push(ajaxCall.responseJSON);
}
});
尝试了以下操作,但值被替换而不是添加:
productOffer.hashedArr = productOffer.hash(productOffer.view);
productOffer.view.forEach(function(el,i){
if(el.id == productOffer.createId){
productOffer.hashedArr[i] = ajaxCall.responseJSON
} else {
productOffer.hashedArr[i] = el;
}
});
for(var key in productOffer.hashedArr){
productOffer.view = [];
productOffer.view.push(productOffer.hashedArr[key]);
}
hash: function(arr){
var arrIndex = Object.create(null);
arr.forEach(function(el){
arrIndex[el.id] = el;
});
console.log('hash ', arrIndex);
return arrIndex;
},
您可以使用
findIndex()
检查数组中是否存在具有相同id的对象,以及它是否用新对象替换它,或者它是否没有将新对象推送到数组中
var-arr=[
{id:1,名字:“约翰”},
{id:2,名字:“Sam”}
]
功能添加或替换(数据,obj){
var i=data.findIndex(函数(e){
返回e.id==obj.id;
});
i!=-1?数据[i]=obj:data.push(obj);
返回数据;
}
log(addOrReplace(arr,{id:1,名称:“lorem”}))
console.log(addOrReplace(arr,{id:3,name:“ipsum”}))
如果您可以使用库,我建议您测试lodash:它可以帮助您处理数组、集合和对象。我不同意,当您掌握.filter
,lodash将变得非常无用,.map
和JS数组提供的其他非常强大的方法。我不明白你想做什么。您是想向数组中的对象添加内容,还是想在数组中添加内容?@KristjanKica add to arrayuse push也许可以?请您展示一下var i=data.findIndex(e=>e.id==obj.id)代码>在简单JS中感谢您引入findIndex()
,但是我的哈希函数有什么问题吗?