DEV Community

Julian Finkler
Julian Finkler

Posted on

JavaScript: Map an array of objects to a dictionary

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"}
Enter fullscreen mode Exit fullscreen mode

Top comments (6)

Collapse
 
richorelse profile image
Ritchie Paul Buitre

Nice, instead how about using Object.fromEntries like so:

let dictionary = Object.fromEntries(data.map(x => [x.id, x.country]));
Enter fullscreen mode Exit fullscreen mode
Collapse
 
allowing_life profile image
Olga Farber

how beautiful! thank you for the idea! and implementation :)

Collapse
 
ariajanke profile image
Aria Janke

terse, and to the point
thank you

Collapse
 
luizhgama profile image
Luiz

thanks

Collapse
 
odeykassam_ profile image
Odey

Hey!! can you explain please why did you use the Rest parameter syntax with ...data?

Collapse
 
allowing_life profile image
Olga Farber

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!