最好的转换方式是什么:

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

to:

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

当前回答

令I = 0; let myArray = ["first", "second", "third", "fourth"]; const arrayToObject = (arr) => 对象。分配(arr{},……。Map (item => ({[i++]: item}))); console.log (arrayToObject (myArray));

或使用

myArray = ["first", "second", "third", "fourth"] console.log (myArray{…})

其他回答

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

console.log ( {…['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'}}
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
    }, {}),
  };
};

我会使用下划线,但如果没有的话我会使用reduce,初始值为空对象{}

>>> ['a', 'b', 'c'].reduce(function(p, c, i) {p[i] = c; return p}, {})
Object { 0="a", 1="b", 2="c"}

reduce应该在今天的大多数浏览器中广泛使用,参见MDN

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

const obj = { ...input }

例子:

const inputArray = ["a", "b", "c"]
const outputObj = { ...inputArray }