Use Array.reduce() to convert the array of objects into a object derived from the array data.
const input = [
{name: 'abc', country : 'US'},
{name: 'xyz', country : 'IN'},
{name: 'mno', country : 'US'},
{name: 'pqr', country : 'IN'}
];
// use reduce to loop over each element and return a constructed object
const output = input.reduce(function(accumulator, element) {
// check to see if there is an entry for this country
if (!accumulator[element.country]) {
// if not create a new array with just this name as the only entry
accumulator[element.country] = [element.name];
} else {
// already exists, push the new value
accumulator[element.country].push(element.name);
}
// return the object
return accumulator;
}, {}); // <- initial value
The variable output results in -
{
"US": [
"abc",
"mno"
],
"IN": [
"xyz",
"pqr"
]
}