DEV Community

Julian Finkler
Julian Finkler

Posted on

23 2

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!

πŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay