Getting 2 values from array of objects

安稳与你 提交于 2021-02-11 13:47:46

问题


I would like to select an item from the dropdown list and would like to set the state of staffId to it. I would like dropdown to show the name, but after I select the name, set the staffid to state. I would also like to achieve this without hardcoding the values in an if-else loop as I have thousands of data to work with.

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":"HOUSE","employeeName":"TEST1", "staffId" : "00001"},
    {"departmentName":"HOUSE","employeeName":"TEST2", "staffId" : "00002"},
    {"departmentName":"HOUSE","employeeName":"TEST3", "staffId" : "00003"}
]

I have created a dropdown in react native with just the emplyeeName. I am using react-native-material-dropdown for the library. I would like to show employeeName but when a user select a name, get an id instead

let staff = this.state.listOfEmployees.map(item => ({
        value: item.employeeName
        staffId: item.staffId
      }));
<Dropdown
    label='Staff Name'
    baseColor='#0079b5'
    data={staff}
    selectedValue={value}
    onChangeText={(staffId) => this.onChangeName(staffId)}
/>

Here in this function, I would like to set the state of staffId to the staffId of the selected value.

onChangeName = (staffId) => {
    //set the state of staffId to the staffId of the selected value.
    //For Example, if AUNG THU 1 is selected, the state of staffId is '00001'.
    this.setState({
       staffId: staffId
    })
}


回答1:


You can do this using the valueExtractor and labelExtractor props. Should look something like this:

<Dropdown
  label='Staff Name'
  baseColor='#0079b5'
  data={staff}
  selectedValue={value}
  valueExtractor={({ staffId }) => staffId}
  labelExtractor={({ employeeName }) => employeeName}
  onChangeText={(staffId) => this.onChangeName(staffId)}
/>


来源:https://stackoverflow.com/questions/59861819/getting-2-values-from-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!