Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
How can I restructure the data where it would group the same IDs?

I have this data where it repeats the items that were placed. How can I group the data according to their id and add an array of variations that will store the various colors and their quantity?

This is the current sample data that I have:

 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
      }
    ];

I just want to know how I could destructure this data to something like this where the duplicated id will be group and then the color and quantity will be pushed inside the variations array:

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

From what I have done, I have merged it already except for the part for the variations array. How can I create the variations array ?

codesandbox: 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 Respostas
Responde à pergunta

0

Initially you have to check if an object with id key is present, if not create it with an empty variations array. then added to the variations array based on the current id

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 Relatório

0

Presented below code-snippet may be helpful to achieve the objective. Please note that this returns an Array and not a map. However, if one removes the Object.values wrapper, then the result will be a map/object with id being the key.

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda