将属性添加到大型对象数组中,而无需手动遍历每个对象

问题描述 投票:1回答:4
export const Schools = [
  {
    value: "Alabama A & M University"
  },
  {
    value: "University of Alabama at Birmingham"
  },
  {
    value: "Amridge University"
  },
  {
    value: "University of Alabama in Huntsville"
  },
  {
    value: "Alabama State University"
  },
  {
    value: "University of Alabama System Office"
  },
  {
    value: "The University of Alabama"
  }, +7000 more schools ]

我需要其中的每一个都有一个键和一个称为文本的字段。 text应该等于value,键应该是唯一的。

如果没有实际通过我的数据在文件中手动通过7000所学校,我怎么能这样做?

例如:

 {
    value: "University of Alabama in Huntsville",
    text: "University of Alabama in Huntsville",
    key: 9,
  },
javascript json
4个回答
4
投票

您可以在导入后在旧数组上应用map运算符来创建新数组

var Schools = [{
    value: "Alabama A & M University"
  },
  {
    value: "University of Alabama at Birmingham"
  },
  {
    value: "Amridge University"
  },
  {
    value: "University of Alabama in Huntsville"
  },
  {
    value: "Alabama State University"
  },
  {
    value: "University of Alabama System Office"
  },
  {
    value: "The University of Alabama"
  }
]
var newVals = Schools.map(function(item, index) {

  return {
    value: item.value,
    text: item.value,
    key: index,
  }
});

console.log(newVals)

0
投票

如果要在O(1)时间内更改值,则应该以不同方式存储数据。这是基于你最初在编辑时所说的内容,但如果你想编辑每个对象,那么上面的人就有正确的答案。

如此:

{
  university_1: { },
  university_2: { },
...
}

然后你做的时候:

obj.university_1.key = something_unique;
obj.university_1.text = some_value;

这可以在没有任何循环的情况下发生,但您需要创建数据以显示我所显示的内容。


0
投票

使用ES6你可以这样做:

var Schools=[{value:"Alabama A & M University"},{value:"University of Alabama at Birmingham"},{value:"Amridge University"},{value:"University of Alabama in Huntsville"},{value:"Alabama State University"},{value:"University of Alabama System Office"},{value:"The University of Alabama"}];

const newArray = Schools.map((o,i) => Object.assign(o, {text: o.value, index: i+1}));
console.log( newArray )

0
投票

尝试使用ES6箭头分配的数组映射():

var schoolData = [{
    value: "Alabama A & M University"
  },
  {
    value: "University of Alabama at Birmingham"
  },
  {
    value: "Amridge University"
  },
  {
    value: "University of Alabama in Huntsville"
  },
  {
    value: "Alabama State University"
  },
  {
    value: "University of Alabama System Office"
  },
  {
    value: "The University of Alabama"
  }];
  
  var result = schoolData.map(obj => Object.assign(obj, {text: obj.value, index: schoolData.indexOf(obj)}));
  
  console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.