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

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

提交回复
热议问题