最好的转换方式是什么:

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

to:

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

当前回答

最短的答案:(使用解构)

const obj = { ...input }

例子:

const inputArray = ["a", "b", "c"]
const outputObj = { ...inputArray }

其他回答

如果你喜欢联机程序,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});
}, {})

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

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

如果你有嵌套数组

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

下面的方法将数组转换为具有特定给定键的对象。

    /**
     * Converts array to object
     * @param  {Array} array
     * @param  {string} key (optional)
     */
    Array.prototype.ArrayToObject = function(key) {
       const array = this;
       const obj = {};

       array.forEach((element, index) => {
           if(!key) {
              obj[index] = element;
           } else if ((element && typeof element == 'object' && element[key])) {
              obj[element[key]] = element;
           }
       });
    return obj;
    }

前任-

[{名称:“测试”},{名称:test1的}].ArrayToObject(“名字”);

会给

{test: {name: 'test'}, test1: {name: 'test1'}}

并且incase key没有作为参数提供给该方法

i.e. [{name: 'test'}, {name: 'test1'}].ArrayToObject();

会给

{0: {name: 'test'}, 1: {name: 'test1'}}

FWIW,另一种最近的方法是使用Object. fromentries和Object。条目如下:

const arr = ['a','b','c'];
arr[-2] = 'd';
arr.hello = 'e';
arr.length = 17;
const obj = Object.fromEntries(Object.entries(arr));

...它允许避免将稀疏数组项存储为未定义或空,并保留非索引(例如,非正整数/非数字)键。

{0: "a", 1: "b", 2: "c", "-2": "d", hello: "e"}

(这里的结果与@Paul Draper的对象相同。分配的答案。)

你可能希望加上arr。长度,但不包括在内:

obj.length = arr.length;

快速和肮脏的#2:

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

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