简体   繁体   中英

Getting 2 values from array of objects

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
    })
}

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)}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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