JavaScript:如何更改数组中对象的属性名称? [英] JavaScript: How can I change property names of objects in an array?
问题描述
我正在使用这个 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' }
]
我无法更改我的数组.如果尝试在我的选项中使用 name
或 value
,我会遇到将它们与 select-react
一起使用的问题.如果我将 name
更改为 value
,则会填充选择选项,但我不想这样做.
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.
谁能教我如何将数组的 name
更改为 value
?
Can anyone teach me how can I change my array's name
to value
?
推荐答案
您可以使用 .map()
函数使 columns
中的数据适合与反应选择
.
You could use the .map()
function to make the data in columns
suitable for use with react-select
.
.map()
函数可用于 Array
类型.它从您调用它的数组创建一个新数组,并允许您提供一个函数,该函数可以在从原始数组复制每个项目时转换/更改每个项目.
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' }
];
*/
有关更多信息,请参阅 MDN 文档对于 .map()
For more information, see the MDN documentation for .map()
这篇关于JavaScript:如何更改数组中对象的属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!