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

179
Visualizações
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 Respostas
Responde à pergunta

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