Tengo la siguiente estructura:
const arr = [ { id: 1, count: 0, parentId: null }, { id: 2, count: 30, parentId: 1 }, { id: 3, count: 1, parentId: 2 } ];y quiero obtener este resultado
const res = [ { id: 1, totalCount: 30 }, { id: 2, totalCount: 31 }, { id: 3, totalCount: 1 }, ]Debe iterar sobre la matriz, filtrar los elementos que coincidan con la identificación principal y sumar los recuentos usando reduce() y agregar eso al recuento existente en cada elemento.
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} ]*/este código le dará el resultado deseado:
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);