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

174
Vistas
group elements of array with same key JSON JavaScript

I don't know how to really reduce the method, I tried to use this to obtain the next JSON, but it obviously did not work.

    {
        "w_elem": [
            {
                "item": [
                    {"type": "type_a","price": "100","discount": "10"},
                    {"type": "type_b","price": "120","discount": "12"},
                    {"type": "type_a","price": "165","discount": "10"}
                ],
                "user": "1001",
                "userType": "A"
            },
            {
                "item": [
                    {"type": "type_a","price": "85","discount": "5"},
                    {"type": "type_a","price": "15","discount": "0"}
                ],
                "user": "1002",
                "userType": "B"
            }
        ]
    }```

  w_elem.forEach(elem => {
    let user= elem.user;

    let aa = Object.values(elem.item.reduce((acc, {type, price, discount}) => {
      acc[type] = acc[type] || {type, price: 0, discount: 0, Count: 0};
      acc[type].price+= Number(price);
      acc[type].discount+= Number(discount);
      acc[type].Count += 1;
      return acc;
    },{}));
  });```

i tried to do the next

        {
            "user": "1001",
            "item": [
                {"type": "type_a","price": "265","discount": "20"},
                {"type": "type_b","price": "120","discount": "12"},
            ]
        },
        {
            "user": "1002",
            "item": [
                {"type": "type_a","price": "85","discount": "5"},
                {"type": "type_b","price": "15","discount": "0"}
            ]
        }
    ]

i dont understand how mantain the struct and only group items by type using reduce

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try this:

let obj = {};
for(const element of data.w_elem){
    if(!obj[element.user]) obj[element.user] = element;
    else{
        obj[element.user].item.push(...element.item);
    }
}
data.w_elem = [...Object.keys(obj).map(e => obj[e])];

Fiddle

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