最好的转换方式是什么:

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

to:

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

当前回答

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

其他回答

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

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

如果你正在使用angularjs,你可以使用angular。Extend,与$的效果相同。jquery的扩展。

var newObj = {};
angular.extend(newObj, ['a','b','c']);

打印稿solutioin:

export const toMap = (errors: ResponseError[]) => {
  const errorMap: Record<string, string> = {};
  errors.forEach(({ field, message }) => {
    errorMap[field] = message;
  });
  return errorMap;
};

export type FieldError = {
  field: string;
  message: string;
};

你可以使用这样的函数:

var toObject = function(array) {
    var o = {};
    for (var property in array) {
        if (String(property >>> 0) == property && property >>> 0 != 0xffffffff) {
            o[i] = array[i];
        }
    }
    return o;
};

这个方法可以更有效地处理稀疏数组。

更面向对象的方法:

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

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

 return Obj;
}