How to return anonymous object from one liner arrow function in javascript?

JavascriptEcmascript 6Arrow Functions

Javascript Problem Overview


I recently switched to es6 and started using arrow functions all over my code. While refactoring I came across below code

data.map(function(d) {
   return {id: d.id, selected: bool};
});

I changed above code to this -

data.map((d) => {id: d.id, selected: bool});

But I was getting error from above code. I don't know what is wrong here? I know that If there is no block of code then there is implicit return provided by arrow function.

But don't know how to return empty object or anonymous object with some properties initialized ?

Edit:

What is wrong if I do it in this way? Just for curiosity sake.

data.map((d) => new {id: d.id, selected: bool});

Javascript Solutions


Solution 1 - Javascript

Put parens around the object initializer:

data.map((d) => ({id: d.id, selected: bool}) );

Parentheses have no effect on the value of the expression inside them, but they do have the syntactic effect of eliminating the ambiguity of the first token of the contained expression. Without the parentheses, the JavaScript parser has to decide whether the { token means "Here starts a function body" or "Here starts an object initializer." It always chooses the former (that is, a block of code).

Introducing the parentheses, therefore, eliminates the confusion: the only thing that a leading ( can mean is "here comes an expression", so that { inside the parentheses can only be "here comes an object initializer." (You can't drop a block of code in the middle of an expression, in other words; if you try, then you'll get a syntax error.)

Solution 2 - Javascript

Hi I think you need to add paranthesis to return object literal

// Parenthesize the body to return an object literal expression: params => ({foo: bar})

from https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Solution 3 - Javascript

You can also use

data.map((d) => {
    return {id: d.id, selected: bool}
} );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWitVaultView Question on Stackoverflow
Solution 1 - JavascriptPointyView Answer on Stackoverflow
Solution 2 - Javascriptsaurabh vyasView Answer on Stackoverflow
Solution 3 - JavascriptPiyush.kapoorView Answer on Stackoverflow