如何获取id与parentId匹配的元素的totalCount
How to get totalCount of elements where id matches parentId
我有以下结构:
const arr = [
{ id: 1, count: 0, parentId: null },
{ id: 2, count: 30, parentId: 1 },
{ id: 3, count: 1, parentId: 2 }
];
我想得到这个结果
const res = [
{ id: 1, totalCount: 30 },
{ id: 2, totalCount: 31 },
{ id: 3, totalCount: 1 },
]
您需要遍历数组,过滤出与父 ID 匹配的项目,并使用 reduce() 对计数求和,并将其添加到每个项目的现有计数中。
const arr = [
{ id: 1, count: 0, parentId: null },
{ id: 2, count: 30, parentId: 1 },
{ id: 3, count: 1, parentId: 2 }
];
const result= [];
arr.forEach((item)=> {
const id = item.id;
const items = arr.filter(x => x.parentId === item.id);
const totalCount = item.count + items.reduce((partialSum, a) => partialSum + a.count, 0);
result.push({id,totalCount})
})
console.log(result); // gives the following
/*[
{id: 1, totalCount:30},
{id: 2, totalCount:31},
{id: 3, totalCount: 1}
]*/
此代码将为您提供所需的结果:
const arr = [
{ id: 1, count: 0, parentId: null },
{ id: 2, count: 30, parentId: 1 },
{ id: 3, count: 1, parentId: 2 }
];
const newArr = arr.map((element) => {
const parent = arr.find((item) => {
return item.parentId === element.id
});
const totalCount = parent ? element.count + parent.count : element.count;
return {id: element.id, totalCount};
});
console.log(newArr);
我有以下结构:
const arr = [
{ id: 1, count: 0, parentId: null },
{ id: 2, count: 30, parentId: 1 },
{ id: 3, count: 1, parentId: 2 }
];
我想得到这个结果
const res = [
{ id: 1, totalCount: 30 },
{ id: 2, totalCount: 31 },
{ id: 3, totalCount: 1 },
]
您需要遍历数组,过滤出与父 ID 匹配的项目,并使用 reduce() 对计数求和,并将其添加到每个项目的现有计数中。
const arr = [
{ id: 1, count: 0, parentId: null },
{ id: 2, count: 30, parentId: 1 },
{ id: 3, count: 1, parentId: 2 }
];
const result= [];
arr.forEach((item)=> {
const id = item.id;
const items = arr.filter(x => x.parentId === item.id);
const totalCount = item.count + items.reduce((partialSum, a) => partialSum + a.count, 0);
result.push({id,totalCount})
})
console.log(result); // gives the following
/*[
{id: 1, totalCount:30},
{id: 2, totalCount:31},
{id: 3, totalCount: 1}
]*/
此代码将为您提供所需的结果:
const arr = [
{ id: 1, count: 0, parentId: null },
{ id: 2, count: 30, parentId: 1 },
{ id: 3, count: 1, parentId: 2 }
];
const newArr = arr.map((element) => {
const parent = arr.find((item) => {
return item.parentId === element.id
});
const totalCount = parent ? element.count + parent.count : element.count;
return {id: element.id, totalCount};
});
console.log(newArr);