Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
Cómo obtener totalCount de elementos donde id coincide con parentId

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 }, ]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!