Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript create a mapping of string to array of objects from an array of objects

Is there a way to create a map (mapping string to array) from an array in the example below using map function? Not sure how to append an object to a key that already exists instead of overwriting what’s inside already

WANT
{"Germany": [{score: 1}], "Austria": [{score: 1}], "Switzerland": [{score: 2},{score: 3}]}

GETTING
{"Germany": [{score: 1}], "Austria": [{score: 1}], "Switzerland": [{score: 3}]}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let data = [
  {country: 'Germany', score: 1},
  {country: 'Austria', score: 1},
  {country: 'Switzerland', score: 2},
  {country: 'Switzerland', score: 3}
];

let dictionary = Object.assign({}, ...data.map((x) => ({[x.country]: [{score: x.score}]})));

>Solution :

Fairly straightforward to do with reduce(), some destructuring and spread syntax:

const data = [
  {country: 'Germany', score: 1},
  {country: 'Austria', score: 1},
  {country: 'Switzerland', score: 2},
  {country: 'Switzerland', score: 3}
];

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

console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading