如何映射数组并生成对象而不是数组?

Sim*_*oyw 1 javascript arrays object ecmascript-6

我想这个代码:

var arr = [
    { key: 'foo', val: 'bar' },
    { key: 'hello', val: 'world' }
];

var result = arr.map((i) => ([i.key]: i.val)); //something like this

console.log(result);
Run Code Online (Sandbox Code Playgroud)

返回:

{foo: 'bar', hello: 'world'}
Run Code Online (Sandbox Code Playgroud)

这在ECMA6中是否可行?

Pra*_*lan 5

Array#map方法用于生成新数组.减少成单个对象的使用Array#reduce方法.

var arr = [{
    key: 'foo',
    val: 'bar'
  },
  {
    key: 'hello',
    val: 'world'
  }
];

// define the property and return the object reference
// where define the initial value as an empty object for result
var result = arr.reduce((obj, o) => (obj[o.key] = o.val, obj), {}); 

console.log(result);
Run Code Online (Sandbox Code Playgroud)