最好的转换方式是什么:

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

其他回答

如果你喜欢联机程序,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});
}, {})

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

console.log ( {…['a', 'b', 'c']} )

如果可以使用Map或Object。分配,很简单。

创建一个数组:

const languages = ['css', 'javascript', 'php', 'html'];

下面的代码创建了一个以index为键的对象:

Object.assign({}, languages)

在地图上复制上面相同的操作

转换为基于索引的对象{0:'css'}等…

const indexMap = new Map(languages.map((name, i) => [i, name] ));
indexMap.get(1) // javascript

转换为一个基于值的对象{css: 'css是伟大的'}等…

const valueMap = new Map(languages.map(name => [name, `${name} is great!`] ));
valueMap.get('css') // css is great

ES5 -解决方案:

使用数组原型函数“push”和“apply”,你可以用数组元素填充对象。

Var arr = ['a','b','c']; var obj = new Object(); Array.prototype.push。应用(obj, arr); console.log (obj);// {'0': 'a', '1': 'b', '2': 'c', length: 3} console.log (obj [2]);/ / c

你可以使用这样的函数:

var toObject = function(array) {
    var o = {};
    for (var property in array) {
        if (String(property >>> 0) == property && property >>> 0 != 0xffffffff) {
            o[i] = array[i];
        }
    }
    return o;
};

这个方法可以更有效地处理稀疏数组。