2转换元件阵列的JavaScript数组转换成目标键值对 [英] Convert JavaScript array of 2 element arrays into object key value pairs

查看:145
本文介绍了2转换元件阵列的JavaScript数组转换成目标键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最快的算法从这样的事情越来越:

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

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

要这样的:

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;
}

这工作得很好,但它似乎有点笨拙。有没有更好的办法?会像<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FReduce\"相对=nofollow>减少()工作,那会是任何更快吗?

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?

推荐答案

您确实可以使用的 Array.prototype.reduce

You could indeed use Array.prototype.reduce:

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

其中, P 是previous迭代的结果,最初 {} C 是数组的当前元素。

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

这是不太可能变得比 array.forEach 越快,但恕我直言,是更清洁。我不相信有任何简单的实现莫过于此。

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.

注:一个函数来做到这正是中已存在下划线库: _.object(阵列)

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

这篇关于2转换元件阵列的JavaScript数组转换成目标键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆