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

前端 未结 16 2426
忘掉有多难
忘掉有多难 2020-11-28 01:08

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 val

相关标签:
16条回答
  • 2020-11-28 01:47

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

    var arr = [
        { key: 'foo', val: 'bar' },
        { key: 'hello', val: 'world' }
    ];
    
    var result = new Map(arr.map(i => [i.key, i.val]));
    
    // When using TypeScript, need to specify type:
    // var result = arr.map((i): [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"}

    0 讨论(0)
  • 2020-11-28 01:50

    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);
    
    console.log(result);
    // Object {foo: Object, hello: Object}
    
    0 讨论(0)
  • 2020-11-28 01:50

    es2015 version:

    const myMap = new Map(objArray.map(obj => [ obj.key, obj.val ]));
    
    0 讨论(0)
  • 2020-11-28 01:50

    Following is small snippet i've created in javascript to convert array of objects to hash map, indexed by attribute value of object. You can provide a function to evaluate the key of hash map dynamically (run time).

    function isFunction(func){
        return Object.prototype.toString.call(func) === '[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 hasmap
     * @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 obj.id+1})
            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 : https://gist.github.com/naveen-ithappu/c7cd5026f6002131c1fa

    0 讨论(0)
提交回复
热议问题