基于id Javascript更新数组



我想在一些条件下基于id更新数组。条件=

const data1 = [
{ type:"foo", id:"123"},
{ type:"bar", id:"124"},
]
const update1 = {type:"bar",id:"123"}
const update2 = {type:"foo", id:"125"}
const update3 = {type:"bar", id:"123"}
  1. console.log(myupdate(data1, update1))

应根据id更新数据1,如下所示这里的类型改为条形

data1 = [ { type:"bar", id:"123"},
{ type:"bar", id:"124"}, ] 

  1. console.log(myupdate(data1, update2)(

此处不存在id为125的项目,因此它添加了一个新的

data1 = [ { type:"bar", id:"123"},
{ type:"bar", id:"124"},
{ type:"foo", id:"125"} ] 


  1. console.log(myupdate(data1, update3))

这里的类型没有改变,所以它应该按原样返回数组。

data1 = [{ type:"bar", id:"123"},
{ type:"bar", id:"124"},
{ type:"foo", id:"125"}
] 

我试过这个代码,但它不工作

const myupdate = (arr, element) => {
arr.map((item)=>{
console.log(item, "ele",element)
if(item.id != element.id){
arr.push(element)
return
}
if(item.id === element.id && item.type === element.type){
return
}
if(item.id === element.id && item.type != element.type){
arr.filter(item => item !== element).push(element)
return
}
})
}

您需要查看数组并找到正确的项。如果没有符合指定要求的项目,您将添加一个新项目。这里有一个例子:

const data = [
{ type: "foo", id: "123"},
{ type: "bar", id: "124"},
]
const update = (data, value) => {
console.log('Updating/Inserting', value);
const existingItem = data.find(item => item.id === value.id);
if (existingItem === undefined) {
data.push(value);
} else {
existingItem.type = value.type;
}
}
console.log('before', data);
update(data, {type:"bar",id:"123"});
console.log(data);
update(data, {type:"foo", id:"125"});
console.log(data);
update(data, {type:"bar", id:"123"});
console.log(data);

最新更新