最好的转换方式是什么:

['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" }

其他回答

我可能会这样写(因为很少有我手边没有下划线库):

var _ = require('underscore');

var a = [ 'a', 'b', 'c' ];
var obj = _.extend({}, a);
console.log(obj);
// prints { '0': 'a', '1': 'b', '2': 'c' }

一个简单和厚脸皮的方法,快速转换数组的项目到一个对象

function arrayToObject( srcArray ){
    return  JSON.parse( JSON.stringify( srcArray ) );
}

然后像这样使用它…

var p = [0,2,3,'pork','pie',6];
obj = new arrayToObject( p );
console.log( obj[3], obj[4] )
// expecting `pork pie`

输出:

pork pie

检查类型:

typeof obj
"object"

如果没有原型方法,事情就不完整

Array.prototype.toObject =function(){
    return  JSON.parse( JSON.stringify( this ) );
}

使用:

var q = [0,2,3,'cheese','whizz',6];
obj = q.toObject();
console.log( obj[3], obj[4] )
// expecting `cheese whizz`

输出:

cheese whizz

*注意,没有命名例程,所以如果你想要特定的名称,那么你将需要继续使用下面现有的方法。


老的方法

这允许您从一个数组生成一个对象,其中的键是按照您想要的顺序定义的。

Array.prototype.toObject = function(keys){
    var obj = {};
    var tmp = this; // we want the original array intact.
    if(keys.length == this.length){
        var c = this.length-1;
        while( c>=0 ){
            obj[ keys[ c ] ] = tmp[c];
            c--;
        }
    }
    return obj;
};

result = ["cheese","paint",14,8].toObject([0,"onion",4,99]);

Console.log (">>>:" + result.onion);将输出"paint",函数必须有相等长度的数组,否则将得到一个空对象。

这里是一个更新的方法

Array.prototype.toObject = function(keys){
    var obj = {};
    if( keys.length == this.length)
        while( keys.length )
            obj[ keys.pop() ] = this[ keys.length ];
    return obj;
};

从Lodash 3.0.0开始,你可以使用_.toPlainObject

var obj = _.toPlainObject(['a', 'b', 'c']); 控制台.log(卷); <script src=“https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js”></script>

为什么没人尝试?在ES6

let arr = ['a','b','c']
let {...obj} = arr
console.log(obj) //  {0: 'a', 1: 'b', 2: 'c'}
let {...obj2} = ['a','b','c']
console.log(obj2) //  {0: 'a', 1: 'b', 2: 'c'}

很简单的方法吗?

使用javascript简化很简单:

["a", "b", "c", "d"].reduce(function(previousValue, currentValue, index) { 
   previousValue[index] = currentValue; 
   return previousValue;
}, 
{}
);

你可以看看Array.prototype.reduce(), https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce