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

431
Views
array.reduce() pero necesita establecer una clave para el valor de retorno

Tengo una matriz en la que estoy usando .reduce para agrupar todas las identificaciones coincidentes de la matriz en una nueva matriz con la identificación.

El problema es que mi salida se ve así

 [ { CHb5591f5db2a546d3af: [ [Object], [Object] ], CH5e86016c8b894d9d87: [ [Object], [Object], [Object], [Object], [Object], [Object] ] } ]

Necesito tener la salida como esta

 [ {id: CHb5591f5db2a546d3af, content: [ [Object], [Object] ]}, {id: CH5e86016c8b894d9d87, content: [ [Object], [Object], [Object], [Object], [Object], [Object] ]} ]

Aquí está mi intento de la función reductora.

 result = await response.reduce(function (a, i) { a[i.messagesId] = a[i.messagesId] || []; //it generates a new property i.messagesId with an array if it does not exist (the value of not existing properties is undefined). if exist, it assign itself a[i.messagesId].push(i); return a; }, Object.create({}));
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Si hay un solo objeto dentro de la matriz, puede lograrlo fácilmente usando Object.entries()

Para fines de demostración, he usado "object" como una cadena

 const arr = [ { CHb5591f5db2a546d3af: [["Object"], ["Object"]], CH5e86016c8b894d9d87: [ ["Object"], ["Object"], ["Object"], ["Object"], ["Object"], ["Object"], ], }, ]; const result = Object.entries(arr[0]).map(([id, content]) => ({ id, content })); console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

Puede ser que esto sea lo que estás buscando. Tenemos un método Array.prototype.reduce() que devuelve nuestra matriz de objetos deseada.

 const array = [ { 'CHb5591f5db2a546d3af': [ { animal: 'Cat', name: 'Tom' }, { animal: 'Dog', name: 'Bruno' } ] }, { 'CH5e86016c8b894d9d87': [ { animal: 'Alligator', name: 'Mike' } ] }, { 'CH5e86016c8b894d9d97': undefined } ] const reducer = function (acc, item) { for (const _key in item) { acc.push({ 'id': _key, 'content': item[_key] }) } return acc; } console.log(array.reduce(reducer, []))

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!