我有两个像下面这样的对象数组,我正在尝试比较两个数组,并在id与arr2匹配的情况下更新arr1的对象总值。
const arr1 = [
{
id: 1,
value: { total: 0 },
},
{
id: 2,
value: { total: 0 },
},
{
id: 3,
value: { total: 0 },
},
id: 4,
value: { total: 0 },
},
];
const arr2 = [
{
id: 2,
value: 3 ,
},
{
id: 3,
value: 5,
},
];我正在尝试比较两个数组,并在id与arr2匹配的情况下更新arr1的对象总值
预期结果为
const arr1 = [
{
id: 1,
value: { total: 0 },
},
{
id: 2,
value: { total: 3 },
},
{
id: 3,
value: { total: 5 },
},
{
id: 4,
value: { total: 0 },
},
];我已经尝试了下面的代码,
arr1.map((item) => {
arr2.find((element) => {
if (element.id === item.id ) {
item = {
...item,
value: {
...item.value,
total: item.value.total + element.value,
},
};
console.log(item);
}
});
return item;
});发布于 2021-10-09 13:30:49
我已经将find函数更改为filter函数,并将结果添加到原始数组中。
尝尝这个
const arr1 = [
{
id: 1,
value: { total: 0 },
},
{
id: 2,
value: { total: 0 },
},
{
id: 3,
value: { total: 0 },
},
{
id: 4,
value: { total: 0 },
}
]
const arr2 = [
{
id: 2,
value: 3 ,
},
{
id: 3,
value: 5,
},
];
arr1.map((item) => {
let result = arr2.filter((element) => element.id == item.id)
if(result && result.length) {
item.value.total += result[0].value
}
return item;
});
console.log(arr1)
发布于 2021-10-09 14:09:55
你必须将map赋值给你的数组:
this.arr1 = this.arr1.map((item) => {
this.arr2.find((element) => {
if (element.id === item.id) {
item = {
...item,
value: {
...item.value,
total: item.value.total + element.value,
},
};
console.log(item);
}
});
return item;
});发布于 2021-10-09 14:14:31
如果每个对象的id是唯一的(在每个数组中),您可以执行以下操作:
arr1.forEach((obj1) => {
const obj2Match = arr2.find((obj2) => obj1.id === obj2.id );
if (obj2Match) {
obj1.value.total += obj2Match.value;
}
});如果多个对象可以具有相同的id (例如,arr2有两个id为2的对象),则可以执行以下操作:
arr1.forEach((obj1) => {
const obj2Matches = arr2.filter((obj2) => obj1.id === obj2.id );
if (obj2Matches.length) {
obj1.value.total += obj2Matches.reduce(((accum, curr) => accum + curr.value), 0);
}
});复杂性:
https://stackoverflow.com/questions/69506908
复制相似问题