JavaScript: Map an array of objects to a dictionary
Julian Finkler

Julian Finkler @devtronic

About: Programmierer aus Leidenschaft. Ich lege besonders Wert auf Clean Code und liebe es mich durch legacy Code zu wühlen... und den dann zu refaktorieren 😉.

Location:
Detmold, Germany
Joined:
Oct 17, 2019

JavaScript: Map an array of objects to a dictionary

Publish Date: Nov 23 '19
39 7

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

Comments 7 total

  • Luiz
    LuizMar 13, 2022

    thanks

  • Aria Janke
    Aria JankeApr 4, 2022

    terse, and to the point
    thank you

  • Odey
    OdeyJul 31, 2022

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

    • Olga Farber
      Olga FarberOct 26, 2022

      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!

  • Olga Farber
    Olga FarberOct 26, 2022

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

  • Ritchie Paul Buitre
    Ritchie Paul BuitreNov 15, 2022

    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
Add comment