Вы можете использовать reduce
и Object.values
следующим образом:
Цель состоит в том, чтобы создать объект с каждым значением country
в качестве ключа и{country: 'a', region: []}
как значение.Затем просто используйте Object.values
, чтобы получить вывод.
const regions=[{country:'a',region:1},{country:'a',region:2},{country:'a',region:3},{country:'b',region:4},{country:'b',region:5},{country:'c',region:6},{country:'d',region:7},{country:'e',region:8}]
const merged = regions.reduce((acc, {country,region}) =>
((acc[country] = acc[country] || {country, region: []}).region.push(region), acc)
, {})
console.log(Object.values(merged))
Вот упрощенная версия приведенного выше кода:
const regions = [{country:'a',region:1},{country:'a',region:2},{country:'a',region:3},{country:'b',region:4},{country:'b',region:5},{country:'c',region:6},{country:'d',region:7},{country:'e',region:8}]
const merged = regions.reduce((acc, {country,region}) => {
acc[country] = acc[country] || {country, region: []};
acc[country].region.push(region);
return acc;
}, {})
console.log(Object.values(merged))