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

105
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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