JavaScript: How can I change property names of objects in an array?

susu watari picture susu watari · Aug 31, 2018 · Viewed 7.9k times · Source

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?

Answer

Dacre Denny picture Dacre Denny · Aug 31, 2018

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