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

169
Views
javascript parsing array of object into a group by array

I'm looking for a way to parse an array of objects, with common object key into a new array with an object with the common key and an array of the common objects. the array looks like this:

[
{
 "name":"Elon",
 "city":"Berlin",
 "salary":5000,
 "age":25
},
{
 "name":"John",
 "city":"Amsterdam",
 "salary":8700,
 "age":28
},{
 "name":"Jacob",
 "city":"Berlin",
 "salary":6500,
 "age":28
},{
 "name":"Lilly",
 "city":"Amsterdam",
 "salary":10000,
 "age":23
},{
 "name":"Mika",
 "city":"Kiev",
 "salary":6800,
 "age":25
}
]

I want to parse it that the array will look like this:

[
{
"city":"Amsterdam",
"ppl":[
{
 "name":"John",
 "salary":8700,
 "age":28
},{
 "name":"Lilly",
 "salary":10000,
 "age":23
}]
},{
"city":"Berlin",
"ppl":[{
 "name":"Elon",
 "salary":5000,
 "age":25
},{
 "name":"Jacob",
 "salary":6500,
 "age":28
}]
},{"city":"Kiev",
"ppl":[{
"name":"Mika",
 "city":"Kiev",
 "salary":6800,
 "age":25
}]}

I've tried using reduce or forEach but it messed up. Any idea or guideness?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use Array#reduce with an object to store the people in each city.

const arr=[{"name":"Elon","city":"Berlin","salary":5000,"age":25},{"name":"John","city":"Amsterdam","salary":8700,"age":28},{"name":"Jacob","city":"Berlin","salary":6500,"age":28},{"name":"Lilly","city":"Amsterdam","salary":10000,"age":23},{"name":"Mika","city":"Kiev","salary":6800,"age":25}];
let res = Object.values(arr.reduce((acc, {city, ...rest})=>
  ((acc[city] ??= {city, ppl: []}).ppl.push(rest), acc), {}));
console.log(res);

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!