Min UD
Min UD

Reputation: 99

setting DropDown values from array of objects

This is the data fetched from WebAPI and stored in a state called items

this.setState({
    items: dataSource
  staffId: ''
})

This state of items will be this.

[
    {"departmentName":"KYAUKSE MAINTENANCE","employeeName":"AUNG THU1", "staffId" : "00001"},
    {"departmentName":"KYAUKSE MAINTENANCE","employeeName":"AUNG THU2", "staffId" : "00002"},
    {"departmentName":"KYAUKSE MAINTENANCE","employeeName":"AUNG THU3", "staffId" : "00003"}
]

I would like to create a dropdown in react native with just the emplyeeName

let staff = [{
      value: 'AUNG THU1',
    }, {
      value: 'AUNG THU2',
    }, {
      value: 'AUNG THU3',
    }];
<Dropdown
    label='Staff Name'
    baseColor='#0079b5'
    data={staff}
    onChangeText={(value) => this.onChangeName(value)}
/>

Edit: Thank you for the answers! I would like to know whether it is possible to get the staffId of the selected value in DropDown? So if i were to select AUNG THU 1, the onChange method would trigger and I would like to set the state of staffId to it.

Upvotes: 0

Views: 79

Answers (2)

SDushan
SDushan

Reputation: 4631

If you want to change your array, try below approach

let dataSource = [
  { departmentName: "KYAUKSE MAINTENANCE", employeeName: "AUNG THU1" },
  { departmentName: "KYAUKSE MAINTENANCE", employeeName: "AUNG THU2" },
  { departmentName: "KYAUKSE MAINTENANCE", employeeName: "AUNG THU3" }
];

let staff = dataSource.map(item => ({
  value: item.employeeName,
  staffId: item.staffId
}));

console.log(staff);

Hope this helps you. Feel free for doubts.

Upvotes: 1

Tom Shaw
Tom Shaw

Reputation: 1712

Double check your Dropdown component. It may be expecting a data array that has both keys and values.

let staff = [{
  key: 'AUNG THU1',
  value: 'AUNG THU1'
}, {
  key: 'AUNG THU2',
  value: 'AUNG THU2'
}, {
  key: 'AUNG THU3',
  value: 'AUNG THU3'
}];

Upvotes: 0

Related Questions