Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return object from arrow function [duplicate]

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?

like image 833
Stepan Suvorov Avatar asked Jun 20 '26 15:06

Stepan Suvorov


2 Answers

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

like image 62
Shushanth Pallegar Avatar answered Jun 22 '26 05:06

Shushanth Pallegar


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

Test:

> a = item => ({id: item.id})
< function item => ({id: item.id})
> a({ id: 5, name: 7 });
< Object {id: 5}
like image 26
Sergiy Pereverziev Avatar answered Jun 22 '26 04:06

Sergiy Pereverziev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!