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,则会填充 select 选项,但我不想这样做。

谁能教我如何将数组的 name 更改为 value

您可以使用 .map() 函数使 columns 中的数据适合与 react-select 一起使用。

.map() 函数在 Array 类型上可用。它从您调用它的数组创建一个新数组,并允许您提供一个函数 transforms/changes 每个项目都是从原始数组复制的。

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

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

更多信息,see the MDN documentation for .map()

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