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

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

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 Report

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