I have following structure:
const arr = [
{ id: 1, count: 0, parentId: null },
{ id: 2, count: 30, parentId: 1 },
{ id: 3, count: 1, parentId: 2 }
];
and I want to get this result
const res = [
{ id: 1, totalCount: 30 },
{ id: 2, totalCount: 31 },
{ id: 3, totalCount: 1 },
]
CodePudding user response:
Yu need to iterate over the array, filter out the items that have the matching the parent id and sum the counts using reduce() and add that to the existing count on each item.
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}
]*/
CodePudding user response:
this code will give you the desired result:
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);