EN
JavaScript - convert array of objects to hash map (indexed by property value)
0
points
In this article, we would like to show you how to convert an array of objects to a hash map in JavaScript.
Quick solution (ES6+):
// ONLINE-RUNNER:browser;
const array = [{ key: 1, value: 'a' }, { key: 2, value: 'b' }];
const result = array.reduce((map, object) => ((map[object.key] = object.value), map), {});
console.log(JSON.stringify(result)); // { '1': 'a', '2': 'b' }
Practical example
In this example, we use reduce()
method to convert an array of objects into a hash map containing key/value pairs created with property values.
// ONLINE-RUNNER:browser;
var array = [
{ key: 1, value: 'a' },
{ key: 2, value: 'b' }
];
var result = array.reduce(function(map, object) {
map[object.key] = object.value;
return map;
}, {});
console.log(JSON.stringify(result)); // { '1': 'a', '2': 'b' }