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

112
Visualizações
how to Group json object based on id in the object

I need to group common objects to single with count,how to group the object based on the id in the object and how to add extra key with count in result.

 var a =[
{"name":"test","id":101,"price":100},
{"name":"test","id":101,"price":100},
{"name":"test3","id":103,"price":10},
{"name":"test2","id":102,"price":12},
]

output =

             [
                {"name":"test","id":101,"price":100,"qty":2},
                {"name":"test3","id":103,"price":10,"qty":1},
                {"name":"test2","id":102,"price":12,"qty":1},
            ]
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Try the following (certainly not the fastest but works ;):

let myarray = [
 {"name":"test","id":101,"price":100},
 {"name":"test","id":101,"price":100},
 {"name":"test3","id":103,"price":10},
 {"name":"test2","id":102,"price":12},
];

let groupedArray = myarray.reduce((acc, cur) => { 
  let foundIndex = acc.findIndex(a => a.id == cur.id); 
  if (foundIndex != -1){ 
     acc[foundIndex].qty += 1  
  } else {
    cur.qty = 1; acc.push(cur) 
  } 
  return acc;
}, []);

// groupedArray contains the grouped objects
about 4 years ago · Juan Pablo Isaza Relatório

0

const a =[
    {"name":"test","id":101,"price":100},
    {"name":"test","id":101,"price":100},
    {"name":"test3","id":103,"price":10},
    {"name":"test2","id":102,"price":12},
];

const output = a.reduce((acc, nv, i, arr) => {
    const item = acc.find(e => e.id === nv.id);
    if(item) return acc;
    acc.push({ ...nv, count: arr.filter(e => e.id === nv.id)?.length });
    return acc;
}, []);
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