简体   繁体   English

如何映射到数组并使用tslint返回对象。 (句法糖)

[英]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: 如何在不使用TSLint声明的情况下使用map遍历数组并返回一个新对象:

This arrow function body can be simplified by omitting the curly braces and the keyword 'return', and wrapping the object literal in parentheses. 可以通过省略花括号和关键字“ return”,并将对象文字括在括号中来简化此箭头函数的主体。

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 [tslint]通过省略花括号和\nkeyword 'return', and wrapping the object literal in parentheses. 关键字“ return”,并将对象文字括在括号中。 (arrow-return-shorthand) (箭头返回简写)\n

And I want to keep the tslint rule arrow-return-shorthand . 我想保留tslint规则arrow-return-shorthand

Simply wrap your object inside () (parenthesis) and remove the function and return statement. 只需将您的对象包装在() (括号)中,然后删除functionreturn语句即可。 The shorthand is below. 简写如下。

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

Further destructuring version would be more shorten. 进一步的destructuring版本将更短。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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