Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

110
Vistas
How to get totalCount of elements where id matches parentId

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 },
]
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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} 
]*/

about 4 years ago · Juan Pablo Isaza Denunciar

0

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);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda