最好的转换方式是什么:

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

to:

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

当前回答

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

其他回答

这是我刚刚写的递归函数。这很简单,而且效果很好。

// Convert array to object
var convArrToObj = function(array){
    var thisEleObj = new Object();
    if(typeof array == "object"){
        for(var i in array){
            var thisEle = convArrToObj(array[i]);
            thisEleObj[i] = thisEle;
        }
    }else {
        thisEleObj = array;
    }
    return thisEleObj;
}

下面是一个例子(jsFiddle):

var array = new Array();
array.a = 123;
array.b = 234;
array.c = 345;
var array2 = new Array();
array2.a = 321;
array2.b = 432;
array2.c = 543;
var array3 = new Array();
array3.a = 132;
array3.b = 243;
array3.c = 354;
var array4 = new Array();
array4.a = 312;
array4.b = 423;
array4.c = 534;
var array5 = new Array();
array5.a = 112;
array5.b = 223;
array5.c = 334;

array.d = array2;
array4.d = array5;
array3.d = array4;
array.e = array3;


console.log(array);

// Convert array to object
var convArrToObj = function(array){
    var thisEleObj = new Object();
    if(typeof array == "object"){
        for(var i in array){
            var thisEle = convArrToObj(array[i]);
            thisEleObj[i] = thisEle;
        }
    }else {
        thisEleObj = array;
    }
    return thisEleObj;
}
console.log(convArrToObj(array));

结果:

我曾多次遇到过这个问题,并决定编写一个尽可能通用的函数。看一看,可以随意修改吗

function typeOf(obj) {
    if ( typeof(obj) == 'object' ) {
        if (obj.length)
            return 'array';
        else
            return 'object';
    } else
    return typeof(obj);
}

function objToArray(obj, ignoreKeys) {
    var arr = [];
    if (typeOf(obj) == 'object') {
        for (var key in obj) {
            if (typeOf(obj[key]) == 'object') {
                if (ignoreKeys)
                    arr.push(objToArray(obj[key],ignoreKeys));
                else
                    arr.push([key,objToArray(obj[key])]);
            }
            else
                arr.push(obj[key]);
        }
    }else if (typeOf(obj) == 'array') {
        for (var key=0;key<obj.length;key++) {
            if (typeOf(obj[key]) == 'object')
                arr.push(objToArray(obj[key]));
            else
                arr.push(obj[key]);
        }
    }
    return arr;
}

如果有人在搜索Typescript方法,我这样写:

const arrayToObject = <T extends Record<K, any>, K extends keyof any>(
  array: T[] = [],
  getKey: (item: T) => K,
) =>
  array.reduce((obj, cur) => {
    const key = getKey(cur)
    return ({...obj, [key]: cur})
  }, {} as Record<K, T>)

它将:

强制第一个参数为对象数组 帮助选择键 强制该键为所有数组项的键

例子:

// from:
const array = [
    { sid: 123, name: 'aaa', extra: 1 },
    { sid: 456, name: 'bbb' },
    { sid: 789, name: 'ccc' }
];
// to:
{
  '123': { sid: 123, name: 'aaa' },
  '456': { sid: 456, name: 'bbb' },
  '789': { sid: 789, name: 'ccc' }
}

用法:

const obj = arrayToObject(array, item => item.sid) // ok
const obj = arrayToObject(array, item => item.extra) // error

这是一个演示。

为了完整性,ECMAScript 2015(ES6)正在传播。将需要一个转译器(Babel)或至少运行ES6的环境。

console.log ( {…['a', 'b', 'c']} )

使用javascript#forEach可以做到这一点

var result = {},
    attributes = ['a', 'b','c'];

attributes.forEach(function(prop,index) {
  result[index] = prop;
});

ECMA6:

attributes.forEach((prop,index)=>result[index] = prop);