Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
-6
rated 0 times [  0] [ 6]  / answers: 1 / hits: 20148  / 6 Years ago, thu, august 30, 2018, 12:00:00

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?


More From » reactjs

 Answers
15

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


[#53594] Tuesday, August 28, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deanna

Total Points: 84
Total Questions: 86
Total Answers: 107

Location: Cyprus
Member since Wed, Dec 8, 2021
3 Years ago
;