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

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

    This is what I'm doing in TypeScript I have a little utils library where I put things like this

    export const arrayToHash = (array: any[], id: string = 'id') => 
             array.reduce((obj, item) =>  (obj[item[id]] = item , obj), {})
    

    usage:

    const hash = arrayToHash([{id:1,data:'data'},{id:2,data:'data'}])
    

    or if you have a identifier other than 'id'

    const hash = arrayToHash([{key:1,data:'data'},{key:2,data:'data'}], 'key')
    

提交回复
热议问题