Home > database >  How can i convert array of objects data into a Countries-Map data format?
How can i convert array of objects data into a Countries-Map data format?

Time:07-12

I have a array of objects data in

const data = [
{ total: 9, country: 'IN' },
{ total: 0, country: 'AF' ]};

But all i need to convert above data into countries Map(plugin) format

data = {IN: { value: 9 },AF: { value: 0}};

Is there any possibilities converting into this format.

Please help me in these issue.

Thanks in Advance

CodePudding user response:

A possible JS solution using map and Object.fromEntries. Im converting to a [key, value] pair array using map and converting to an Object using Object.fromEntries

const data = [
{ total: 9, country: 'IN' },
{ total: 0, country: 'AF' }];

const res = Object.fromEntries(data.map(({total,country}) => [country,{value: total}]))

console.log(res)

CodePudding user response:

Just reduce() to an object:

const data = [
  { total: 9, country: 'IN' },
  { total: 0, country: 'AF' }
];

const result = data.reduce((a, {country, total}) => ({
  ...a,
  [country]: {value: total}
}), {});

console.log(result);

  • Related