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

前端 未结 16 2548
忘掉有多难
忘掉有多难 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}

提交回复
热议问题