最好的转换方式是什么:

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

to:

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

当前回答

ECMAScript 6引入了易于多填充的Object.assign:

Object.assign()方法用于复制所有对象的值 可枚举对象拥有的属性,从一个或多个源对象到目标 对象。它将返回目标对象。

Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}

数组本身的length属性不会被复制,因为它是不可枚举的。

此外,你可以在对象上使用ES8扩展语法来实现相同的结果:

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

对于自定义键,您可以使用reduce:

['a', 'b', 'c'].reduce((a, v) => ({ ...a, [v]: v}), {}) 
// { a: "a", b: "b", c: "c" }

其他回答

快速和肮脏的#2:

var i = 0
  , s = {}
  , a = ['A', 'B', 'C'];

while( i < a.length ) { s[i] = a[i++] };

我们可以使用Object。赋值和数组。reduce函数将数组转换为对象。 Var arr = [{a:{b:1}},{c:{d:2}}] var newObj = arr。reduce((a, b) =>对象。赋值(a, b), {}) console.log (newObj)

为了完整起见,这里有一个O(1) ES2015方法。

var arr = [1, 2, 3, 4, 5]; // array, already an object
Object.setPrototypeOf(arr, Object.prototype); // now no longer an array, still an object

var finalResult = ['a','b','c']。Map ((item, index) => ({[index]: item})); console.log (finalResult)

更面向对象的方法:

Array.prototype.toObject = function() {
 var Obj={};

 for(var i in this) {
  if(typeof this[i] != "function") {
   //Logic here
   Obj[i]=this[i];
  }
 }

 return Obj;
}