DEV Community

loading...

JavaScript: Map an array of objects to a dictionary

devtronic profile image Julian Finkler ・1 min read

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"}

Discussion (1)

Collapse
lukaszahradnik profile image
Lukáš Zahradník

The same thing using reduce

let dictionary = data.reduce((a,x) => ({...a, [x.id]: x.country}), {})
Enter fullscreen mode Exit fullscreen mode
Forem Open with the Forem app