最好的转换方式是什么:

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

to:

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

当前回答

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

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

其他回答

为什么没人尝试?在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'}

很简单的方法吗?

这不是直接相关的,但我来这里寻找一个合并嵌套对象如一行

const nodes = {
    node1: {
        interfaces: {if1: {}, if2: {}}
    },
    node2: {
        interfaces: {if3: {}, if4: {}}
    },
    node3: {
        interfaces: {if5: {}, if6: {}}
    },
}

解决方案是结合使用reduce和对象扩展:

const allInterfaces = nodes => Object.keys(nodes).reduce((res, key) => ({...res, ...nodes[key].interfaces}), {})

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

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});
}, {})

打印稿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;
};