首页 > 解决方案 > JavaScript: How can I change property names of objects in an array?

问题描述

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?

标签: javascriptreactjsreact-select

解决方案


您可以使用该.map()功能使数据columns适合与react-select.

.map()功能在Array类型上可用。它从您调用它的数组创建一个新数组,并允许您提供一个函数,该函数在从原始数组复制每个项目时转换/更改它。

您可以按如下方式使用它:

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' }
];
*/

有关详细信息,请参阅 MDN 文档.map()


推荐阅读