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+):
xxxxxxxxxx
1
const array = [{ key: 1, value: 'a' }, { key: 2, value: 'b' }];
2
3
const result = array.reduce((map, object) => ((map[object.key] = object.value), map), {});
4
5
console.log(JSON.stringify(result)); // { '1': 'a', '2': 'b' }
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.
xxxxxxxxxx
1
var array = [
2
{ key: 1, value: 'a' },
3
{ key: 2, value: 'b' }
4
];
5
6
var result = array.reduce(function(map, object) {
7
map[object.key] = object.value;
8
return map;
9
}, {});
10
11
console.log(JSON.stringify(result)); // { '1': 'a', '2': 'b' }