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


Use Case

The use case is to convert an array of objects into a hash map based on string or function provided to evaluate and use as the key in the hash map and value as an object itself. A common case of using this is converting an array of objects into a hash map of objects.


The following is a small snippet in JavaScript to convert an array of objects to a hash map, indexed by the attribute value of object. You can provide a function to evaluate the key of hash map dynamically (run time). Hope this helps someone in future.

function isFunction(func) {
    return === '[object Function]';

 * This function converts an array to hash map
 * @param {String | function} key describes the key to be evaluated in each object to use as key for hashmap
 * @returns Object
 * @Example 
 *      [{id:123, name:'naveen'}, {id:345, name:"kumar"}].toHashMap("id")
 *      Returns :- Object {123: Object, 345: Object}
 *      [{id:123, name:'naveen'}, {id:345, name:"kumar"}].toHashMap(function(obj){return})
 *      Returns :- Object {124: Object, 346: Object}
Array.prototype.toHashMap = function(key) {
    var _hashMap = {}, getKey = isFunction(key)?key: function(_obj){return _obj[key];};
    this.forEach(function (obj){
        _hashMap[getKey(obj)] = obj;
    return _hashMap;

You can find the gist here: Converts Array of Objects to HashMap.

4/30/2020 9:59:48 PM

Using ES6 Map (pretty well supported), you can try this:

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

var result = new Map( => [i.key, i.val]));

// When using TypeScript, need to specify type:
// var result = [string, string] => [i.key, i.val])

// Unfortunately maps don't stringify well.  This is the contents in array form.
console.log("Result is: " + JSON.stringify([...result])); 
// Map {"foo" => "bar", "hello" => "world"}


With lodash, this can be done using keyBy:

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

var result = _.keyBy(arr, o => o.key);

// Object {foo: Object, hello: Object}

Using ES6 spread + Object.assign:

array = [{key: 'a', value: 'b', redundant: 'aaa'}, {key: 'x', value: 'y', redundant: 'zzz'}]

const hash = Object.assign({}, => ({[s.key]: s.value})));

console.log(hash) // {a: b, x: y}

Using the spread operator:

const result = arr.reduce(
    (accumulator, target) => ({ ...accumulator, [target.key]: target.val }),

Demonstration of the code snippet on jsFiddle.


You can use the new Object.fromEntries() method.


const array = [
   {key: 'a', value: 'b', redundant: 'aaa'},
   {key: 'x', value: 'y', redundant: 'zzz'}

const hash = Object.fromEntries( => [e.key, e.value])

console.log(hash) // {a: b, x: y}