在 JavaScript 中将平面数组 [k1,v1,k2,v2] 转换为对象 {k1:v1,k2:v2}? [英] Convert flat array [k1,v1,k2,v2] to object {k1:v1,k2:v2} in JavaScript?
问题描述
javascript 中是否有一种简单的方法可以将平面数组转换为对象,其中数组的偶数索引成员作为属性,奇数索引成员作为相应的值(类似于 ruby 的 Hash[*array]
)?
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]
)?
例如,如果我有这个:
[ 'a', 'b', 'c', 'd', 'e', 'f' ]
那么我想要这个:
{ '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?)
我正在寻找 vanilla 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 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().
这篇关于在 JavaScript 中将平面数组 [k1,v1,k2,v2] 转换为对象 {k1:v1,k2:v2}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!