最好的转换方式是什么:

['a','b','c']

to:

{
  0: 'a',
  1: 'b',
  2: 'c'
}

当前回答

.reduce((o,v,i)=>(o[i]=v,o), {})

(文档)

或者更冗长

var trAr2Obj = function (arr) {return arr.reduce((o,v,i)=>(o[i]=v,o), {});}

or

var transposeAr2Obj = arr=>arr.reduce((o,v,i)=>(o[i]=v,o), {})

最短的一个香草JS

JSON.stringify([["a", "X"], ["b", "Y"]].reduce((o,v,i)=>{return o[i]=v,o}, {}))
=> "{"0":["a","X"],"1":["b","Y"]}"

更复杂的例子

[["a", "X"], ["b", "Y"]].reduce((o,v,i)=>{return o[v[0]]=v.slice(1)[0],o}, {})
=> Object {a: "X", b: "Y"}

甚至更短(通过使用函数(e) {console.log(e);} === (e)=>(console.log(e),e))

 nodejs
> [[1, 2, 3], [3,4,5]].reduce((o,v,i)=>(o[v[0]]=v.slice(1),o), {})
{ '1': [ 2, 3 ], '3': [ 4, 5 ] }

[/ docs]

其他回答

我将使用Array.of()简单地做到这一点。Array of有能力使用它的context作为构造函数。

注2:of函数是一个有意通用的工厂方法;它 不要求它的this值是数组构造函数。 因此,它可以传递给其他构造函数或由其他构造函数继承 可以使用单个数值参数调用。

因此,我们可以将array .of()绑定到一个函数,并生成类似object的数组。

虚函数(){}; var thingy = Array.of.apply(dummy,[1,2,3,4]); console.log(页面);

通过使用array .of(),甚至可以进行数组子类化。

如果你喜欢联机程序,IE8不再是一个问题(因为它应该是)

['a','b','c'].reduce((m,e,i) => Object.assign(m, {[i]: e}), {});

继续在浏览器控制台上尝试它

它可以像这样更啰嗦:

['a','b','c'].reduce(function(memo,elm,idx) {
    return Object.assign(memo, {[idx]: elm});
}, {});

但还是排除了IE8的可能性。如果必须使用IE8,那么你可以像这样使用lodash/下划线:

_.reduce(['a','b','c'], function(memo,elm,idx) {
    return Object.assign(memo, {[idx]: elm});
}, {})

一个快速而肮脏的问题:

var obj = {},
  arr = ['a','b','c'],
  l = arr.length; 

while( l && (obj[--l] = arr.pop() ) ){};

如果你使用ES6,你可以使用Object。赋值运算符和展开运算符

{ ...['a', 'b', 'c'] }

如果你有嵌套数组

var arr=[[1,2,3,4]]
Object.assign(...arr.map(d => ({[d[0]]: d[1]})))

这不是直接相关的,但我来这里寻找一个合并嵌套对象如一行

const nodes = {
    node1: {
        interfaces: {if1: {}, if2: {}}
    },
    node2: {
        interfaces: {if3: {}, if4: {}}
    },
    node3: {
        interfaces: {if5: {}, if6: {}}
    },
}

解决方案是结合使用reduce和对象扩展:

const allInterfaces = nodes => Object.keys(nodes).reduce((res, key) => ({...res, ...nodes[key].interfaces}), {})