The easiest way for converting an array of objects to a dictionary in JavaScript / TypeScript:
let data = [
{id: 1, country: 'Germany', population: 83623528},
{id: 2, country: 'Austria', population: 8975552},
{id: 3, country: 'Switzerland', population: 8616571}
];
let dictionary = Object.assign({}, ...data.map((x) => ({[x.id]: x.country})));
// {1: "Germany", 2: "Austria", 3: "Switzerland"}
Top comments (6)
Nice, instead how about using
Object.fromEntries
like so:how beautiful! thank you for the idea! and implementation :)
terse, and to the point
thank you
thanks
Hey!! can you explain please why did you use the Rest parameter syntax with ...data?
it's because data is an array, so its map is also an array, and when you use ...data - it spreads the array elements to be function parameters, which get to be one-prop objects, with which the resulting object is updated. Beautiful!