Create options list for react Select from single dimension array

Viewed 34

I have an array like [ 123, 456 ] and it needs to be mapped into a react Select with label and value pairs so the "options" will be: 0: {label: "123", value: 123} 1: {label: "456", value: 456}

I just can't seem to get the map syntax to work for the source array (i.e. 0: 123, 1: 456)

2 Answers

You can write like this:

array.map((item)=> <Option label={item} value={item}/>)

This return an array of holding options with your label and value

If you need the options array you can write this:

let Myarray= [ 123, 456 ];
Myarray.map((item)=> <Option label={item} value={item}/>)

or If you need an array with label and value:

let Myarray= [ 123, 456 ];
let FinalArray=[];
Myarray.map((item)=>[...FinalArray,{label:item,value:item}])

if you want to put " to value

let Myarray= [ 123, 456 ];
let FinalArray=[];
Myarray.map((item)=>[...FinalArray,{label:item.toString(),value:item}])
Related