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

前端 未结 16 2493
忘掉有多难
忘掉有多难 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: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) );

提交回复
热议问题