javascript - 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
?
解决方案
您可以使用该.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()
推荐阅读
- sql - 按最常见的重复值分组
- c++ - 为什么在 x64 中忽略 __stdcall 调用约定?
- ruby-on-rails - Postgresql 汇总以前日期的所有唯一值
- javascript - RequireJS 路径和 require-css 如何结合起来?
- amazon-web-services - 在 AWS 上寻找有关 ETL 流程的指导/替代方案
- sql-server - 将值插入 SQL 中的简单表时出现什么问题?
- database - 如何搜索 100 亿条记录?
- generics - 是否可以编写一个通用的 rust 函数来告诉您给定的枚举变体是否在容器中?
- c# - C# 从字段继承属性
- python - 如何以更有效的方式实现这个数组算法?