繁体   English   中英

JavaScript:如何更改数组中对象的属性名称?

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

我正在使用这个react-selecthttps : //github.com/JedWatson/react-select

他们需要的选项数据的格式是:

const options = [
    { value: 'chocolate', label: 'Chocolate' },
    { value: 'strawberry', label: 'Strawberry'},
    { value: 'vanilla', label: 'Vanilla' }
];

我的阵列设置不同,如下所示:

const columns = [
    { name: 'OrderNumber', title: 'Order Number' },
    { name: 'strawberry', title: 'Strawberry' },
    { name: 'vanilla', title: 'Vanilla' }
]

我无法更改我的数组。 如果尝试在我的选项中使用namevalue ,我会遇到在select-react使用它们的问题。 如果我将name更改为value ,则会填充选择选项,但是我不想这样做。

谁能教我如何将数组的name更改为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' }
];
*/

有关更多信息, 请参阅.map()的 MDN 文档

如果您只想将name属性重命名为value您可以使用map并将name属性破坏为value并选择其余的。

 const columns = [ { name: 'OrderNumber', title: 'Order Number' }, { name: 'strawberry', title: 'Strawberry' }, { name: 'vanilla', title: 'Vanilla' } ]; const newColumns = columns.map( item => { const { name: value, ...rest } = item; return { value, ...rest } } ); console.log( newColumns );

但是,我怀疑您会想要这个,因为react-selecttitle不起作用(据我所知)。 我猜它在等待label道具。 如果是这样,请按照@Dacre Denny 的建议更改所有属性。 我喜欢箭头函数 :) 所以:

const newColumns = columns.map( item =>
  ( { value: item.name, label: item.title } )
);

使用具有重命名属性的destructuring将简化。

 const options = [ { value: "chocolate", label: "Chocolate" }, { value: "strawberry", label: "Strawberry" }, { value: "vanilla", label: "Vanilla" }, ]; const columns = options.map(({ value: name, label: title }) => ({ name, title, })); console.log(columns);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM