如何返回匿名对象从一个线性箭头函数在 javascript?

我最近切换到 es6,并开始在我的代码中使用箭头函数。 在重构时,我偶然发现了下面的代码

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

我把上面的代码改成了这个

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

但是上面的代码出错了,我不知道哪里出错了? 我知道如果没有代码块,那么就会有箭头函数提供的隐式返回。

但是不知道如何返回一些初始化属性的空对象或匿名对象?

编辑:

如果我这样做有什么错? 只是出于好奇。

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

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

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

You can also use

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