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

后端 未结 5 887
陌清茗
陌清茗 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:51

    You could indeed use Array.prototype.reduce:

    function objectify(array) {
        return array.reduce(function(p, c) {
             p[c[0]] = c[1];
             return p;
        }, {});
    }
    

    where p is the result of the previous iteration, initially {}, and c is the current element of the array.

    It's unlikely to be any faster than array.forEach, but it is IMHO cleaner. I don't believe there's any simpler implementation than this.

    NB: a function to do exactly this already exists in the Underscore library: _.object(array)

提交回复
热议问题