Return object from arrow function [duplicate]

2019-08-10 12:22发布

问题:

This question already has an answer here:

  • ECMAScript 6 arrow function that returns an object 4 answers

I want to output object from arrow function (in a short form), so full code is:

somemethod(function(item) {
   return {id: item.id};
})

with arrow functions it's:

somemethod((item) => {
   return {id: item.id};
})

and now short form should be something like:

somemethod(item = > {id: item.id} )

that does not work, as well as this one:

somemethod(item = > {{id: item.id}} )

only one solution I found for now is to use create Object notation:

somemethod(item = > new Object({id: item.id}) )

is there another way?

回答1:

somemethod(item => ({ id: item.id }))

Test:

> a = item => ({id: item.id})
< function item => ({id: item.id})
> a({ id: 5, name: 7 });
< Object {id: 5}


回答2:

For Objects you have wrap your object using parentheses or else it doesn't work

This is because the code inside braces ({}) is parsed as a sequence of statements

Try as below

var func = () => ({ foo: 1 });

refer : arrow functions