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}]}
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);