Utilize the Array.reduce()
method to transform an array of objects into a new object based on the array data.
const input = [
{name: 'abc', country : 'US'},
{name: 'xyz', country : 'IN'},
{name: 'mno', country : 'US'},
{name: 'pqr', country : 'IN'}
];
// Implement reduce to iterate over each element and create a new object
const output = input.reduce(function(accumulator, element) {
// Check if there is a record for this country
if (!accumulator[element.country]) {
// If not, create an array with only this name as the element
accumulator[element.country] = [element.name];
} else {
// If it already exists, add the new value to the array
accumulator[element.country].push(element.name);
}
// Return the updated object
return accumulator;
}, {}); // <- initial value
The variable output
will yield:
{
"US": [
"abc",
"mno"
],
"IN": [
"xyz",
"pqr"
]
}