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

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

    There are better ways to do this as explained by other posters. But if I want to stick to pure JS and ol' fashioned way then here it is:

    var arr = [
        { key: 'foo', val: 'bar' },
        { key: 'hello', val: 'world' },
        { key: 'hello', val: 'universe' }
    ];
    
    var map = {};
    for (var i = 0; i < arr.length; i++) {
        var key = arr[i].key;
        var value = arr[i].val;
    
        if (key in map) {
            map[key].push(value);
        } else {
            map[key] = [value];
        }
    }
    
    console.log(map);
    

提交回复
热议问题