Convert JavaScript array of 2 element arrays into object key value pairs

后端 未结 5 894
陌清茗
陌清茗 2020-11-29 10:58

What is the fastest algorithm for getting from something like this:

var array = [ [1,\'a\'], [2,\'b\'], [3,\'c\'] ];

to something like this

5条回答
  •  难免孤独
    2020-11-29 11:37

    You can wrap the entire thing within Array.prototype.reduce, like this

    function objectify(array) {
        return array.reduce(function(result, currentArray) {
            result[currentArray[0]] = currentArray[1];
            return result;
        }, {});
    }
    
    console.log(objectify([ [1, 'a'], [2, 'b'], [3, 'c'] ]));
    # { '1': 'a', '2': 'b', '3': 'c' }
    

    We are just accumulating the key-value pairs in the result object and finally the result of reduce will be the result object and we are returning it as the actual result.

提交回复
热议问题