简体   繁体   English

简化为 typescript 的映射

[英]Reduce to map of type typescript

I have this configurations我有这个配置

type Option = {
  value: any,
  label: any
}

And

export interface Role {
  id: number
  name: string
}

Then I have Roles然后我有角色

const roles:Role[]:[
{id:1,name:'name1'},
{id:2,name:'name2'},
{id:3,name:'name3'}
]

I want to extract Option[] from that roles dataset.我想从该角色数据集中提取Option[] How do i do it in javascript?我如何在javascript中做到这一点?

In java I could dojava中我可以做

roles.stream().map(role->new Option(role.id,role.name)).collect(collectors.toList());

You can just map() the roles to options:您可以将角色map()到选项:

type Option = {
  value: any;
  label: any;
}

interface Role {
  id: number;
  name: string;
}

const roles: Role[] = [
  {id: 1, name: 'name1'},
  {id: 2, name: 'name2'},
  {id: 3, name: 'name3'}
];

const options: Option[] = roles.map(({id, name}) => ({value: id, label: name}));

Playground link 游乐场链接

Typescript Playground link 打字稿游乐场链接

type Option = {
  value: any,
  label: any
}

interface Role {
  id: number
  name: string
}

const roles: Role[] = [
  { id: 0, name: "foo" },
  { id: 1, name: "bar" },
  { id: 2, name: "baz" },
]

const result: Option[] = roles
  .map(({ id, name }) => ({ label: id, value: name }));

console.log(result);

Result:结果:

[LOG]: [{
  "label": 0,
  "value": "foo"
}, {
  "label": 1,
  "value": "bar"
}, {
  "label": 2,
  "value": "baz"
}]

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

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