简体   繁体   中英

Create options for react-select

The react-select component requires that the input parameters be in this structure

const options = [
    { value: 'chocolate', label: 'Chocolate' },
    { value: 'strawberry', label: 'Strawberry' },
    { value: 'vanilla', label: 'Vanilla' }
  ]

The props I am passing to this custom component has structure like this.

members :[
    {
      MemberName: "name of person"
      other fields
    },
    {
      MemberName: "name of person"
      other fields
    }
 ]

The members array will be dynamic coming in from the parent component.

I am trying to create my input for the react-select element which I believe at the end should look like this

const options = [
    { value: 'Member 1 Name', label: 'Member 1 Name' },
    { value: 'Member 2 Name', label: 'Member 2 Name' },
    ...as many members as the props has
  ]

So far I have tried Map, forEach, reduce and simple for loop as well. But I am struggling to transform this.

Map is the right way.

Try this:

let options = members.map(member => ({
  label: member.MemberName,
  value: member.something
}))

It's not clear where your other values come from. Your samples don't use the same strings, which makes it impossible for us to infer what relationship exists between the source data and the desired output.

If the proper string for value exists as-is on these member objects, then you can just copy it over like I did with MemberName . If the proper value must be calculated based on member props, you'll have to write that transformation logic. SO could do this, but you would need to update your question to use consistent values in all your samples.

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