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 convertir múltiples objetos en una matriz en un nuevo objeto?

Digamos que tengo una matriz a continuación:

 [ { type: 'senior', schoolName: 'school-A', country: 'America' }, { type: 'senior', schoolName: 'school-B', country: 'England' }, { type: 'junior', schoolName: 'school-C', country: 'German' }, { type: 'junior', schoolName: 'school-D', country: 'Italy' }, ]

¿Cómo puedo convertir la matriz anterior en un objeto como se muestra a continuación?

 { senior: { America: 'school-A', England: 'school-B' }, junior: { German: 'school-C', Italy: 'school-D' } }

¿Cuál es la forma sintácticamente más limpia de lograr esto?

¡¡Gracias por cualquier ayuda!!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Una forma podría ser reducir su conjunto de objetos a un solo objeto. Para cada iteración, puede acumular su objeto (inicialmente comenzando como un objeto vacío {} ), para contener la clave de type actual junto con el nuevo par clave-valor para el país y el nombre de la escuela. Al usar la sintaxis extendida ... puede fusionar el objeto visto anteriormente en la clave de type (de su objeto acumulado actual) con el nuevo objeto que está construyendo.

Vea los comentarios de código en el siguiente ejemplo:

 const arr = [ { type: 'senior', schoolName: 'school-A', country: 'America' }, { type: 'senior', schoolName: 'school-B', country: 'England' }, { type: 'junior', schoolName: 'school-C', country: 'German' }, { type: 'junior', schoolName: 'school-D', country: 'Italy' }, ]; const res = arr.reduce((acc, {type, schoolName, country}) => ({ // obtain the kys from the current object using destructuring assignment ...acc, // merge the current object stored in acc into the current object `{}` we're building [type]: { // using "computed property names" ...acc[type], // merge inner object (still worrks when acc[type] === undefined) [country]: schoolName } }), {}); // start with an initial empty object `{}` that we'll accumulate to console.log(res);

Difundir su objeto en cada iteración podría verse como ineficiente, por lo que puede acumular la referencia de objeto único en su lugar (que en este punto, podría valer la pena usar un bucle for estándar for mejorar la legibilidad):

 const arr = [ { type: 'senior', schoolName: 'school-A', country: 'America' }, { type: 'senior', schoolName: 'school-B', country: 'England' }, { type: 'junior', schoolName: 'school-C', country: 'German' }, { type: 'junior', schoolName: 'school-D', country: 'Italy' }, ]; const res = arr.reduce((acc, {type, schoolName, country}) => { if(!acc[type]) acc[type] = {}; acc[type][country] = schoolName; return acc; }, {}); console.log(res);

about 4 years ago · Juan Pablo Isaza Report

0

Creo que esta es una solución simple y legible para su problema (si aparecen varias instancias del mismo country en el mismo type la última ocurrencia anulará todas las ocurrencias anteriores)

 let data = [ { type: 'senior', schoolName: 'school-A', country: 'America' }, { type: 'senior', schoolName: 'school-B', country: 'England' }, { type: 'junior', schoolName: 'school-C', country: 'German' }, { type: 'junior', schoolName: 'school-D', country: 'Italy' }, ]; let res = {}; data.forEach(e => { if(!res[e.type]) res[e.type] = {}; res[e.type][e.country] = e.schoolName; }); console.log(res);

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!