[英]merge object array in array of objects
我有两个 arrays,所以我想将数组中的值分配给对象数组,如果有相同的 id 这是我的代码,但 foreach 重复第一个数组,
let cars =[
{
sap_code:"audi",
products:[
{id:23,name:"a4"},
{id:55,name:"a5"},
]
},
{
sap_code:"chevi",
products:[
{id:23,name:"x4"},
{id:55,name:"x5"},
]
}
]
let cars2= [{id:55, value:25000}]
let joinCar = []
cars.forEach((value)=> {
value.products.forEach((value2)=>{
const existing = cars2.filter((v, i)=> {
return (v.id == value2.id);
});
if (existing.length) {
value2.value = existing[0].value;
joinCar.push(value)
} else {
value2.value = null;
joinCar.push(value);
}
});
})
我想要这样的东西
[
{
sap_code:"audi",
products:[
{id:23,name:"a4"},
{id:55,name:"a5", value:25000},
]
},
{
sap_code:"chevi",
products:[
{id:23,name:"x4"},
{id:55,name:"x5", value:25000},
{id:29,name:"x6"},
]
}
]
在外部forEach
中push
,而不是在内部推动。
let cars =[ { sap_code:"audi", products:[ {id:23,name:"a4"}, {id:55,name:"a5"}, ] }, { sap_code:"chevi", products:[ {id:23,name:"x4"}, {id:55,name:"x5"}, ] } ] let cars2= [{id:55, value:25000}] let joinCar = [] cars.forEach((value)=> { value.products.forEach((value2)=>{ const existing = cars2.filter((v, i)=> { return (v.id == value2.id); }); if (existing.length) { value2.value = existing[0].value; } else { value2.value = null; } }); joinCar.push(value); }) console.log(joinCar);
使用for-of和 A rray.prototype.find()
let cars =[ { sap_code:"audi", products:[ {id:23,name:"a4"}, {id:55,name:"a5"}, ] }, { sap_code:"chevi", products:[ {id:23,name:"x4"}, {id:55,name:"x5"}, ] } ] let cars2 = [{id:55, value:25000}] const joinCar = [...cars] // you originally created a new array for(const {products} of joinCar) for(const product of products) { const car2 = cars2.find(({id})=>id===product.id) if(car2) product.value = car2.value } console.log(joinCar)
我认为如果您使用hashtable
并reduce
,可以显着降低复杂性。 因此,最好的方法是创建一个带有cars2
的 id 和值的哈希表,以便找到匹配项并在cars
上使用reduce
,如下所示:
let cars =[ { sap_code:"audi", products:[ {id:23,name:"a4"}, {id:55,name:"a5"}, ] }, { sap_code:"chevi", products:[ {id:23,name:"x4"}, {id:55,name:"x5"}, ] } ] let cars2= [{id:55, value:25000}]; var hasTable = {}; for(let i of cars2){ hasTable[i.id] = i.value //create a hashtable with id and values } cars.reduce((a,v)=>{ let val = v.products.find(k=> hasTable[k.id]); if(val){ val.value = hasTable[val.id]; } return a }) console.log(cars)
let cars =[ { sap_code:"audi", products:[ {id:23,name:"a4"}, {id:55,name:"a5",value:4500}, ] }, { sap_code:"chevi", products:[ {id:23,name:"x4"}, {id:55,name:"x5"}, ] } ]; let cars2 = [{id:55, value:25000}]; cars.forEach(car=>{ cars2.forEach(newCar=>{ let fc = car.products.findIndex(c=>c.id===newCar.id); if (fc.==-1) car.products[fc].value=newCar;value; }); }). console.log(JSON.stringify(cars))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.