1

I would like that this code:

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

Returns:

{foo: 'bar', hello: 'world'}

Is this possible in ECMA6?

Simoyw
  • 681
  • 1
  • 9
  • 30

3 Answers3

5

The Array#map method is using to generate a new array. To reduce into a single object use Array#reduce method.

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);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

You could use the forEach method:

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

var obj = {};
arr.forEach(function(item){
  obj[item.key] = item.val;
});

console.log(obj);
Christos
  • 53,228
  • 8
  • 76
  • 108
0

You can do this with Array.prototype.reduce:

arr.reduce(function(map, obj) {
    map[obj.key] = obj.val;
    return map;
}, {});
erikamjoh
  • 107
  • 1
  • 6