简体   繁体   中英

How to map on a array and return a object with tslint. (syntactic sugar)

This is a pure syntactic sugar question.

How can I iterate over a array with map and return a new object without having TSLint saying:

This arrow function body can be simplified by omitting the curly braces and the keyword 'return', and wrapping the object literal in parentheses.

For example, the object user:

 class User { constructor( public id: number, public first_name: string, public last_name: string, public gender: Date, public location: number, ) } 

And when I do this :

 const simple_users = users.map(u => { return { name: u.name, id: u.id} }); 

Then this happens :

\n[tslint] This arrow function body can be simplified by omitting the curly braces and the \nkeyword 'return', and wrapping the object literal in parentheses.  (arrow-return-shorthand) \n

And I want to keep the tslint rule arrow-return-shorthand .

Simply wrap your object inside () (parenthesis) and remove the function and return statement. The shorthand is below.

const simple_users = users.map(u => ({ name: u.name, id: u.id}));

Further destructuring version would be more shorten.

const simple_users = users.map(({name, id}) => ({ name, id}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM