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

Discussion (3)

Collapse
ariajanke profile image
Aria Janke

terse, and to the point
thank you

Collapse
luizhgama profile image
Luiz

thanks