最好的转换方式是什么:

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

to:

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

当前回答

更面向对象的方法:

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

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

 return Obj;
}

其他回答

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

很简单的方法吗?

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

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

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

ECMA6:

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

var finalResult = ['a','b','c']。Map ((item, index) => ({[index]: item})); console.log (finalResult)

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']);