转换平面数组[K1,V1,K2,V2]对象{K1:V1,K2:V2}在JavaScript中? [英] Convert flat array [k1,v1,k2,v2] to object {k1:v1,k2:v2} in JavaScript?

查看:274
本文介绍了转换平面数组[K1,V1,K2,V2]对象{K1:V1,K2:V2}在JavaScript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在JavaScript一个简单的方法把一个平面阵列,并转换成一个对象数组作为属性和奇次成员的相应值(analgous Ruby的哈希的偶次会员[*阵列] )?

Is there a simple way in javascript to take a flat array and convert into an object with the even-indexed members of the array as properties and odd-indexed members as corresponding values (analgous to ruby's Hash[*array])?

例如,如果我有这样的:

For example, if I have this:

[ 'a', 'b', 'c', 'd', 'e', 'f' ]

然后我想这样的:

Then I want this:

{ 'a': 'b', 'c': 'd', 'e': 'f' }

我想出迄今最好的似乎更详细的比它必须是:

The best I've come up with so far seems more verbose than it has to be:

var arr = [ 'a', 'b', 'c', 'd', 'e', 'f' ];
var obj = {};
for (var i = 0, len = arr.length; i < len; i += 2) {
    obj[arr[i]] = arr[i + 1];
}
// obj => { 'a': 'b', 'c': 'd', 'e': 'f' }

有没有更好的,更简洁,更优雅的方式来做到这一点? (或者我刚刚在Ruby编程太多了吗?)

Is there a better, less verbose, or more elegant way to do this? (Or I have just been programming in ruby too much lately?)

我正在寻找在香草的javascript的答案,但也有兴趣,如果有一个更好的方式使用,如果做到这一点 undercore.js 的jQuery 。性能是不是一个真正的问题。

I'm looking for an answer in vanilla javascript, but would also be interested if there is a better way to do this if using undercore.js or jQuery. Performance is not really a concern.

推荐答案

pretty肯定这将工作和更短:

Pretty sure this will work and is shorter:

var arr = [ 'a', 'b', 'c', 'd', 'e', 'f' ];
var obj = {};
while (arr.length) {
    obj[arr.shift()] = arr.shift();
}

请参阅shift().

这篇关于转换平面数组[K1,V1,K2,V2]对象{K1:V1,K2:V2}在JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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