Convert object array to hash map, indexed by an attribute value of the Object

This is fairly trivial to do with Array.prototype.reduce:

var arr = [
    { key: 'foo', val: 'bar' },
    { key: 'hello', val: 'world' }
];

var result = arr.reduce(function(map, obj) {
    map[obj.key] = obj.val;
    return map;
}, {});

console.log(result);
// { foo:'bar', hello:'world' }

Note: Array.prototype.reduce() is IE9+, so if you need to support older browsers you will need to polyfill it.

Leave a Comment