Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!