最好的转换方式是什么:

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

to:

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

当前回答

import books from "./books.json";

export const getAllBooks = () => {
  return {
    data: books,
    // a=accoumulator, b=book (data itelf), i=index
    bookMap: books.reduce((a, book, i) => {
      // since we passed {} as initial data, initially a={}
      // {bookID1:book1, bookID2:i}
      a[book.id] = book;
      // you can add new property index
      a[book.id].index=i
      return a;
      // we are passing initial data structure
    }, {}),
  };
};

其他回答

如果你正在使用jquery:

$.extend({}, ['a', 'b', 'c']);

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

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

如果你有嵌套数组

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

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

很简单的方法吗?

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

为了完整起见,这里有一个O(1) ES2015方法。

var arr = [1, 2, 3, 4, 5]; // array, already an object
Object.setPrototypeOf(arr, Object.prototype); // now no longer an array, still an object