最好的转换方式是什么:

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

to:

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

当前回答

令I = 0; let myArray = ["first", "second", "third", "fourth"]; const arrayToObject = (arr) => 对象。分配(arr{},……。Map (item => ({[i++]: item}))); console.log (arrayToObject (myArray));

或使用

myArray = ["first", "second", "third", "fourth"] console.log (myArray{…})

其他回答

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

更多的浏览器支持和更灵活的方法是使用一个正常的循环,比如:

const arr = ['a', 'b', 'c'],
obj = {};

for (let i=0; i<arr.length; i++) {
   obj[i] = arr[i];
}

但现代的方法也可以使用展开运算符,比如:

{...arr}

或对象赋值:

Object.assign({}, ['a', 'b', 'c']);

两者都会返回:

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

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;

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

    /**
     * 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'}}

ES5 -解决方案:

使用数组原型函数“push”和“apply”,你可以用数组元素填充对象。

Var arr = ['a','b','c']; var obj = new Object(); Array.prototype.push。应用(obj, arr); console.log (obj);// {'0': 'a', '1': 'b', '2': 'c', length: 3} console.log (obj [2]);/ / c