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

108
Visualizações
Get quantity in object respective with the category

I want the result to sum all the quantity of same cat.

    var  data = [
         { cat: 'EK-1',name:"test",info:"mat", quantity: 3},
         { cat: 'EK-2', name:"test2",info:"nat"quantity: 1}
          ];

I have array of object having some similar objects. How to add quantity and create unique object? This is what I tried.

var data = [{
    cat: 'EK-1',
    name: "test",
    info: "mat",
    quantity: 1
  },
  {
    cat: 'EK-1',
    name: "test",
    info: "mat",
    quantity: 1
  },
  {
    cat: 'EK-1',
    name: "test",
    info: "mat",
    quantity: 1
  },
  {
    cat: 'EK-2',
    name: "test2",
    info: "nat",
    quantity: 1
  }
];

const products = Array.from(data.reduce((acc, {
    cat,
    quantity
  }) =>
  acc.set(cat, (acc.get(cat) || 0) + quantity),
  new Map()
), ([cat, quantity]) => ({
  cat,
  quantitya
}));

console.log(products);

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could get the complete object as value for the map and increment quantity.

const
    data = [{ cat: 'EK-1', name: "test", info: "mat", quantity: 1 }, { cat: 'EK-1', name: "test", info: "mat", quantity: 1 }, { cat: 'EK-1', name: "test", info: "mat", quantity: 1 }, { cat: 'EK-2', name: "test2", info: "nat", quantity: 1 }],
    products = Array.from(
          data
              .reduce(
                  (acc, o) => acc.set(o.cat, { ...o, quantity: (acc.get(o.cat)?.quantity || 0) + o.quantity }),
                  new Map
              )
              .values()
    );

console.log(products);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

You first group and sum quantities under categories keys, using reduce and then you discard those keys with Object.values.

 var data = [{
        cat: 'EK-1',
        name: "test",
        info: "mat",
        quantity: 1
    },
    {
        cat: 'EK-1',
        name: "test",
        info: "mat",
        quantity: 1
    },
    {
        cat: 'EK-1',
        name: "test",
        info: "mat",
        quantity: 1
    },
    {
        cat: 'EK-2',
        name: "test2",
        info: "nat",
        quantity: 1
    }];


const result = Object.values(data.reduce((acc, item) => {
  if (!acc[item.cat]) {
    acc[item.cat] = item;
  } else {
    acc[item.cat] = { ...item, quantity: item.quantity + acc[item.cat].quantity }
  }
  return acc;      
}, {}))
        

console.log(result)

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