Reputation: 13326
Why is this working:
return elements.map((e)=> {return Object.assign({}, e, {selected:true})});
But this doesn't:
return elements.map((e)=> {...e, {selected: true}});
?
New to ES6 / Babel / React, have mercy.
UPDATE: After moving to this (as suggested):
return elements.map(e => ({...e, selected: true }));
Though the spread is working elsewhere in the project:
return [
...state,
element(undefined, action)
]
Upvotes: 6
Views: 7112
Reputation: 4228
An implicit return of an object from an arrow function should be wrapped in parens so the interpreter knows it's not a block.
So return elements.map(e => ({...e, selected: true }));
Also fixed the syntax for the selected property, it shouldn't be wrapped in brackets as azium pointed out.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Your unexpected token error is probably due to babel not supporting the proposed object spread. Array spread is es6. Using the plugin as in the answer below will solve this issue. My preferred way to include object spread is babel stage 0, as you also get other cool features like the ::
binding operator. Object spread is stage 2, so you could also use that if you don't want to include stages 1 and 0.
https://babeljs.io/docs/plugins/preset-stage-0/
Upvotes: 15
Reputation: 12966
The Object rest spread transform from the ES7 spec is not supported by Babel out of the box. You'll need to use a plugin for that.
To install this plugin:
npm i babel-plugin-transform-object-rest-spread --save-dev
Then, add this to your .babelrc
{
"plugins": ["transform-object-rest-spread"]
}
More info here
Upvotes: 0