javascript - Convert js Array to Dictionary/Hashmap - Stack Overflow

PHOTO EMBED

Sun Oct 23 2022 15:46:04 GMT+0000 (Coordinated Universal Time)

Saved by @arielvol #javascript

const test = [
    { nation: { name: "Germany", iso: "DE", rankingPoints: 293949 } },
    { nation: { name: "Hungary", iso: "HU", rankingPoints: 564161 } },
    { nation: { name: "Serbia", iso: "SR", rankingPoints: 231651 } }
];    

const sorted = test.sort((a, b) => a.nation.rankingPoints - b.nation.rankingPoints);

// Using forEach:

var dict = {}
sorted.forEach((el, index) => dict[el.nation.iso] = sorted.length - index);

// Using reduce:

dict = sorted.reduce(
    (dict, el, index) => (dict[el.nation.iso] = sorted.length - index, dict),
    {}
);

console.log(dict)
console.log("dict['DE'] = ", dict['DE'])
content_copyCOPY

https://stackoverflow.com/questions/50802528/convert-js-array-to-dictionary-hashmap