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?
>Solution :
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);