I have a js array as follows.
[{"id":"1","name":"John","city":"London"},
{"id":"2","name":"Paul","city":"Darvin"},
{"id":"1","name":"Ron","city":"Paris"},
{"id":"2","name":"Will","city":"Tokyo"},
{"id":"3","name":"Dave","city":"Oslo"}]
I want to concat values in "name" and "city" based on "id" values. The final result should look like this.
[{"id":"1","name":"John,Ron","city":"London,Paris"},
{"id":"2","name":"Paul,Will","city":"Darvin,Tokyo"},
{"id":"3","name":"Dave","city":"Oslo"}]
CodePudding user response:
Group array of objects by key.
var arr = [{"id":"1","name":"John","city":"London"},
{"id":"2","name":"Paul","city":"Darvin"},
{"id":"1","name":"Ron","city":"Paris"},
{"id":"2","name":"Will","city":"Tokyo"},
{"id":"3","name":"Dave","city":"Oslo"}]
var result = Object.values(arr.reduce(function(agg, item) {
agg[item.id] ??= {id: item.id, name: [], city: []}
agg[item.id].name.push(item.name)
agg[item.id].city.push(item.city)
return agg
}, {})).map(function(item) {
item.city = item.city.join(",");
item.name = item.name.join(",");
return item;
})
console.log(result);