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

13

我正在使用这个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吗?


你不能转换你的数组并以某种方式提供给 react-select 吗? - devserkan
3个回答

23
你可以使用.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() 的文档


11
如果您只想将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 } )
);

4

使用重命名属性的解构可以使代码更简洁。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接