Home > Mobile >  Reduce to map of type typescript
Reduce to map of type typescript

Time:06-23

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. How do i do it in javascript?

In java I could do

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

CodePudding user response:

You can just map() the roles to options:

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

CodePudding user response:

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"
}]
  • Related