最好的转换方式是什么:

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

to:

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

当前回答

如果你正在使用jquery:

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

其他回答

下面的方法将数组转换为具有特定给定键的对象。

    /**
     * Converts array to object
     * @param  {Array} array
     * @param  {string} key (optional)
     */
    Array.prototype.ArrayToObject = function(key) {
       const array = this;
       const obj = {};

       array.forEach((element, index) => {
           if(!key) {
              obj[index] = element;
           } else if ((element && typeof element == 'object' && element[key])) {
              obj[element[key]] = element;
           }
       });
    return obj;
    }

前任-

[{名称:“测试”},{名称:test1的}].ArrayToObject(“名字”);

会给

{test: {name: 'test'}, test1: {name: 'test1'}}

并且incase key没有作为参数提供给该方法

i.e. [{name: 'test'}, {name: 'test1'}].ArrayToObject();

会给

{0: {name: 'test'}, 1: {name: 'test1'}}

这是一个解决方案在coffeescript

arrayToObj = (arr) ->
  obj = {}
  for v,i in arr
    obj[i] = v if v?
  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'}

很简单的方法吗?

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

一个快速而肮脏的问题:

var obj = {},
  arr = ['a','b','c'],
  l = arr.length; 

while( l && (obj[--l] = arr.pop() ) ){};