将 2 个元素数组的 JavaScript 数组转换为对象键值对 [英] Convert JavaScript array of 2 element arrays into object key value pairs
问题描述
从这样的东西中获取最快的算法是什么:
var array = [ [1,'a'], [2,'b'], [3,'c'] ];
像这样:
Object { 1: "a", 2: "b", 3: "c" }
到目前为止,这是我想出的:
function objectify(array) {var 对象 = {};array.forEach(函数(元素){对象[元素[0]] = 元素[1];});返回对象;}
工作正常,但似乎有点笨拙.有没有更好的办法?会像 reduce() 工作,那会更快吗?
你确实可以使用 Array.prototype.reduce
:
function objectify(array) {返回 array.reduce(function(p, c) {p[c[0]] = c[1];返回 p;}, {});}
其中 p
是前一次迭代的结果,最初是 {}
,c
是数组的当前元素.>
它不太可能比 array.forEach
快,但恕我直言,它更干净.我认为没有比这更简单的实现了.
注意:Underscore 库中已经存在一个完全执行此操作的函数:_.object(数组)
What is the fastest algorithm for getting from something like this:
var array = [ [1,'a'], [2,'b'], [3,'c'] ];
to something like this:
Object { 1: "a", 2: "b", 3: "c" }
so far this is what i've come up with:
function objectify(array) {
var object = {};
array.forEach(function(element) {
object[element[0]] = element[1];
});
return object;
}
which works fine, but it seems kind of clumsy. Is there a better way? Would something like reduce() work and would that be any faster?
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)
这篇关于将 2 个元素数组的 JavaScript 数组转换为对象键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!