I am using this react-select
: https://github.com/JedWatson/react-select
The format for options data that they require is:
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry'},
{ value: 'vanilla', label: 'Vanilla' }
];
My array is set up differently as follows:
const columns = [
{ name: 'OrderNumber', title: 'Order Number' },
{ name: 'strawberry', title: 'Strawberry' },
{ name: 'vanilla', title: 'Vanilla' }
]
I am not able to change my array. If try to use name
or value
in my option items, I encounter issues using them with select-react
. If I change my name
to value
, the select options are populating, however I don't want to do that.
Can anyone teach me how can I change my array's name
to value
?
To update an object in a JavaScript array, you can use “findIndex()” method for executing each array element and updating the object values accordingly, the “for” loop method for iterating through an array and updating the specified value, and “map()” method for mapping the updated value to an object.
After you have created an object, you can set or change its properties by calling the property directly with the dot operator (if the object inherits from IDL_Object) or by calling the object's SetProperty method.
join() combines all array elements into a string. concat combines two arrays together or add more items to an array and then return a new array. push() adds item(s) to the end of an array and changes the original array. unshift() adds an item(s) to the beginning of an array and changes the original array.
You could use the .map()
function to make the data in columns
suitable for use with react-select
.
The .map()
function is available on the Array
type. It creates a new array from the array you call it on, and allows you to provide a function that transforms/changes each item as it is copied from the original array.
You can make use of it as follows:
const columns = [
{ name: 'OrderNumber', title: 'Order Number' },
{ name: 'strawberry', title: 'Strawberry' },
{ name: 'vanilla', title: 'Vanilla' }
]
const options = columns.map(function(row) {
// This function defines the "mapping behaviour". name and title
// data from each "row" from your columns array is mapped to a
// corresponding item in the new "options" array
return { value : row.name, label : row.title }
})
/*
options will now contain this:
[
{ value: 'OrderNumber', label: 'Order Number' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
];
*/
For more information, see the MDN documentation for .map()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With