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

前端 未结 16 2425
忘掉有多难
忘掉有多难 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:25

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

    Example:

    const array = [
       {key: 'a', value: 'b', redundant: 'aaa'},
       {key: 'x', value: 'y', redundant: 'zzz'}
    ]
    
    const hash = Object.fromEntries(
       array.map(e => [e.key, e.value])
    )
    
    console.log(hash) // {a: b, x: y}

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

    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.

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

    Using the spread operator:

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

    Demonstration of the code snippet on jsFiddle.

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

    Using simple Javascript

    var createMapFromList = function(objectList, property) {
        var objMap = {};
        objectList.forEach(function(obj) {
          objMap[obj[property]] = obj;
        });
        return objMap;
      };
    // objectList - the array  ;  property - property as the key
    
    0 讨论(0)
  • 2020-11-28 01:26

    try

    let toHashMap = (a,f) => a.reduce((a,c)=> (a[f(c)]=c,a),{});
    

    let arr=[
      {id:123, name:'naveen'}, 
      {id:345, name:"kumar"}
    ];
    
    let fkey = o => o.id; // function changing object to string (key)
    
    let toHashMap = (a,f) => a.reduce((a,c)=> (a[f(c)]=c,a),{});
    
    console.log( toHashMap(arr,fkey) );
    
    // Adding to prototype is NOT recommented:
    //
    // Array.prototype.toHashMap = function(f) { return toHashMap(this,f) };
    // console.log( arr.toHashMap(fkey) );

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

    With lodash:

    const items = [
        { key: 'foo', value: 'bar' },
        { key: 'hello', value: 'world' }
    ];
    
    const map = _.fromPairs(items.map(item => [item.key, item.value]));
    
    console.log(map); // { foo: 'bar', hello: 'world' }
    

    Link to lodash

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