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

时间:2018-03-04 03:21:41

标签: javascript json

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的字段。 text应该等于value,键应该是唯一的。

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

前:

 {
    value: "University of Alabama in Huntsville",
    text: "University of Alabama in Huntsville",
    key: 9,
  },

4 个答案:

答案 0 :(得分: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)




答案 1 :(得分:0)

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

如此:

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

然后当你这样做:

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

这可以在没有任何循环的情况下发生,但您需要创建数据以便在我展示时看起来。

答案 2 :(得分: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 )

答案 3 :(得分:0)

使用ES6箭头分配尝试Array map():



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