Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

195
Vistas
¿Cómo puedo reestructurar los datos donde agruparían las mismas ID?

Tengo este dato donde repite los elementos que se colocaron. ¿Cómo puedo agrupar los datos según su identificación y agregar una serie de variaciones que almacenarán los distintos colores y su cantidad?

Estos son los datos de muestra actuales que tengo:

 const data = [ { id: "aRLMZkiSU7T0lcsPCSsV", name: "Tumbler", price: 200, size: "500", cat: "ML", color: "Green", quantity: 2 }, { id: "aRLMZkiSU7T0lcsPCSsV", name: "Tumbler", price: 200, size: "500", cat: "ML", color: "Pink", quantity: 1 }, { id: "aRLMZkiSU7T0lcsPCSsV", name: "Tumbler", price: 200, size: "500", cat: "ML", color: "Black", quantity: 11 }, { id: "y9ECyZBKp2OBekmWym4M", name: "Notebook", price: 250, size: "200", cat: "CM", color: "Red", quantity: 1 }, { id: "y9ECyZBKp2OBekmWym4M", name: "Notebook", price: 250, size: "200", cat: "CM", color: "Green", quantity: 4 } ];

Solo quiero saber cómo podría desestructurar estos datos a algo como esto donde la identificación duplicada se agrupará y luego el color y la cantidad se insertarán dentro de la matriz de variaciones:

 id: "aRLMZkiSU7T0lcsPCSsV", name: "Tumbler", price: 200, size: "500", cat: "ML", variations: [ {name: "Green", quantity: 1}, {name: "Black", quantity: 10}, ]

Por lo que he hecho, ya lo he fusionado excepto por la parte de la matriz de variaciones. ¿Cómo puedo crear la matriz de variations ?

códigos y caja: https://codesandbox.io/s/data-restructure-u2ss8z?file=/src/App.js

 const mapById = data.reduce( (acc, { id, name, size, cat, price, color, quantity }) => { acc[id] = { id, name, size, cat, price, color, quantity }; return acc; }, {} );
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Inicialmente, debe verificar si un objeto con clave de id está presente, si no, créelo con una matriz de variations vacía. luego se agrega a la matriz de variaciones según la id actual

 const data = [ { id: "aRLMZkiSU7T0lcsPCSsV", name: "Tumbler", price: 200, size: "500", cat: "ML", color: "Green", quantity: 2 }, { id: "aRLMZkiSU7T0lcsPCSsV", name: "Tumbler", price: 200, size: "500", cat: "ML", color: "Pink", quantity: 1 }, { id: "aRLMZkiSU7T0lcsPCSsV", name: "Tumbler", price: 200, size: "500", cat: "ML", color: "Black", quantity: 11 }, { id: "y9ECyZBKp2OBekmWym4M", name: "Notebook", price: 250, size: "200", cat: "CM", color: "Red", quantity: 1 }, { id: "y9ECyZBKp2OBekmWym4M", name: "Notebook", price: 250, size: "200", cat: "CM", color: "Green", quantity: 4 } ]; const mapById = data.reduce( (acc, { id, name, size, cat, price, color, quantity }) => { acc[id] ??= {id,name,size,cat,price,variations:[]} acc[id].variations.push({name:color, quantity}) return acc; }, {} ); console.log(mapById)

about 4 years ago · Juan Pablo Isaza Denunciar

0

El fragmento de código que se presenta a continuación puede ser útil para lograr el objetivo. Tenga en cuenta que esto devuelve una Array y no un mapa. Sin embargo, si se elimina el envoltorio Object.values , el resultado será un mapa/objeto con id como clave.

 const regroupArray = arr => ( Object.values( arr.reduce( (acc, {id, color, quantity, ...rest}) => ( id in acc ? { ...acc, [id]: { ...acc[id], variations: acc[id].variations.concat([{ color, quantity }]) } } : { ...acc, [id]: { id, ...rest, variations: [{ color, quantity }] } } ), {} ) ) ); const data = [ { id: "aRLMZkiSU7T0lcsPCSsV", name: "Tumbler", price: 200, size: "500", cat: "ML", color: "Green", quantity: 2 }, { id: "aRLMZkiSU7T0lcsPCSsV", name: "Tumbler", price: 200, size: "500", cat: "ML", color: "Pink", quantity: 1 }, { id: "aRLMZkiSU7T0lcsPCSsV", name: "Tumbler", price: 200, size: "500", cat: "ML", color: "Black", quantity: 11 }, { id: "y9ECyZBKp2OBekmWym4M", name: "Notebook", price: 250, size: "200", cat: "CM", color: "Red", quantity: 1 }, { id: "y9ECyZBKp2OBekmWym4M", name: "Notebook", price: 250, size: "200", cat: "CM", color: "Green", quantity: 4 } ]; console.log(regroupArray(data));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda