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

374
Views
Matriz de objetos: cómo agrupar elementos por propiedad y agrupar datos de cada uno de los elementos agrupados en 1

Estoy tratando de realizar una operación en la matriz que se describe en el tema. Lo que ya he hecho: agrupar por propiedad común + asignar datos de cada elemento al formato deseado. Se logró mediante el uso de la función reducir + mapa dentro de él. Ahora necesito la parte final que aplastará cada una de las propiedades de los elementos agrupados en 1. Mi objetivo es hacer que funcione correctamente, idealmente extendiendo la función de reestructuración.

Matriz para reestructurar

 const arrToRestructure = [ { x: "test-x1", y: "test-y1", data: [ {id: 1, label: "label-y1-1"}, {id: 2, label: "label-y1-2"} ] }, { x: "test-x2", y: "test-y1", data: [ {id: 1, label: "label-y1-3"}, {id: 2, label: "label-y1-4"} ] }, { x: "test-x2", y: "test-y2", data: [ {id: 1, label: "label-y2-1"}, {id: 2, label: "label-y2-2"} ] }, ]

función de reestructuración

 const restructureArr = () => { const restructuredArr = arrToRestructure.reduce( (prevVal, nextVal) => ({ ...prevVal, [nextVal["y"]]: [ ...(prevVal[nextVal["y"]] || []), nextVal.data.map((nextVal) => nextVal.label), ]}) ,[]); return restructuredArr; }

salida de corriente

 { "test-y1": [ [ "label-y1-1", "label-y1-2" ], [ "label-y1-3", "label-y1-4" ] ], "test-y2": [ [ "label-y2-1", "label-y2-2" ] ] }

salida deseada

 { "test-y1": [ "label-y1-1", "label-y1-2", "label-y1-3", "label-y1-4", ], "test-y2": [ "label-y2-1", "label-y2-2" ] }
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Simplemente distribuya el resultado de Array#map cada vez:

 const restructureArr = () => { const restructuredArr = arrToRestructure.reduce((prevVal, nextVal) => ({ ...prevVal, [nextVal["y"]]: [ ...(prevVal[nextVal["y"]] || []), ...nextVal.data.map((nextVal) => nextVal.label), // fix ] }) , []); return restructuredArr; }

Algunas mejoras:

 const restructureArr = (arrToRestructure = []) => arrToRestructure.reduce((acc, { y, data = [] }) => ({ ...acc, [y]: [ ...(acc[y] || []), ...data.map(({ label }) => label), ] }), []); const arrToRestructure = [ { x: "test-x1", y: "test-y1", data: [ {id: 1, label: "label-y1-1"}, {id: 2, label: "label-y1-2"} ] }, { x: "test-x2", y: "test-y1", data: [ {id: 1, label: "label-y1-3"}, {id: 2, label: "label-y1-4"} ] }, { x: "test-x2", y: "test-y2", data: [ {id: 1, label: "label-y2-1"}, {id: 2, label: "label-y2-2"} ] } ]; console.log(restructureArr(arrToRestructure));

about 4 years ago · Juan Pablo Isaza Report

0

Puede agrupar según el valor y usando array#reduce . Empuje toda la etiqueta para el mismo valor y usando array#forEach .

 const arrToRestructure = [ { x: "test-x1", y: "test-y1", data: [ {id: 1, label: "label-y1-1"}, {id: 2, label: "label-y1-2"} ] }, { x: "test-x2", y: "test-y1", data: [ {id: 1, label: "label-y1-3"}, {id: 2, label: "label-y1-4"} ] }, { x: "test-x2", y: "test-y2", data: [ {id: 1, label: "label-y2-1"}, {id: 2, label: "label-y2-2"} ] }, ], result = arrToRestructure.reduce((r, {y, data}) => { r[y] ??= []; data.forEach(({label}) => r[y].push(label)); return r; },{}); console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

Otra solución sería usar Object.entries y .flat() .

 const obj = { "test-y1": [ [ "label-y1-1", "label-y1-2" ], [ "label-y1-3", "label-y1-4" ] ], "test-y2": [ [ "label-y2-1", "label-y2-2" ] ] } const e = Object.entries(obj).map(el => ({[el[0]]: el[1].flat()})) let o = Object.fromEntries(e.map(x => [Object.keys(x), Object.values(x)[0]])) console.log(o);

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!