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

91
Views
Cómo reducir la matriz a objeto con subclaves

Parece que no puedo entender la función JS array.reduce(). Tengo la siguiente matriz de entrada y quiero transformarla en un objeto con reducción para obtener el siguiente resultado:

Aporte:

 let cars = [ { name: 'bmw', type: 'diesel' }, { name: 'mercedes', type: 'gas' }, { name: 'honda', type: 'electric' }, { name: 'bmw', type: 'gas' } ];

Salida deseada:

 { "bmw": [{type: 'diesel'}, {type: 'gas'}], "mercedes": [{"type": "gas"}], "honda": [{"type": "electric"}] }

Lo que he probado:

 let output = input.reduce((acc, item) => { if (!acc[item.name]) { acc[item.name] = [{ type: item.type }]; } else { acc[item.name] = []; // How can I add the value of the second bmw occurrence into the array? } return acc; }, {}); console.log(output);

Lo que tengo:

 { "bmw": [], "mercedes": [{"type": "gas"}], "honda": [{"type": "electric"}] }

Cualquier sugerencia es muy apreciada como novato de JS aquí. ¡Gracias!

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Puede difundir el valor de matriz existente y agregar un nuevo valor

 let output = cars.reduce((acc, item) => { if (!acc[item.name]) { acc[item.name] = [{ type: item.type }]; } else { acc[item.name] = [...acc[item.name], { type: item.type }]; // spread and insert } return acc; }, {});

Referencia https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

about 4 years ago · Santiago Trujillo Report

0

Esta es básicamente la misma lógica que la solución de kwaiks. Las principales diferencias son que esto no infiere la veracidad de si una entrada está definida, sino que pregunta explícitamente sobre la propiedad y, en lugar de difundir, simplemente usa el método push.

 let output = cars.reduce((acc, currentValue, currentIndex, arr) => { acc.hasOwnProperty(currentValue.name) ? acc[currentValue.name].push({type: currentValue.type}) : acc[currentValue.name] = [{type: currentValue.type}]; return acc; }, {});

Si no tiene la intención de volver a declarar la salida, es posible que desee intercambiar let con const .

about 4 years ago · Santiago Trujillo 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!