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?

0

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

It says ther is a syntax error in your snippet.
@WasteD : I think your browser not supports ES6 arrow function
Might be the problem ty.
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);

Comments

0

You can do this with Array.prototype.reduce:

arr.reduce(function(map, obj) {
    map[obj.key] = obj.val;
    return map;
}, {});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.