从相同的结构创建对象数组

时间:2020-03-19 17:25:18

标签: javascript

我有以下保持相同结构的对象数组:

var fieldObjects = [{
  AllowGridEditing: 'FALSE',
  DisplayName: 'Submit',
  RealFieldName: 'SubmitField',
  Name: 'SubmitField',
  FieldType: 'Text',
  Type: 'Text',
  Filterable: 'FALSE',
  Sortable: 'FALSE',
  ReadOnly: 'TRUE',
}, {
  AllowGridEditing: 'FALSE',
  DisplayName: 'Hours Up',
  RealFieldName: 'HoursUpField',
  Name: 'HoursUpField',
  FieldType: 'Text',
  Type: 'Text',
  Filterable: 'FALSE',
  Sortable: 'FALSE',
  ReadOnly: 'TRUE',
}, {
  AllowGridEditing: 'FALSE',
  DisplayName: 'Personal Hours',
  RealFieldName: 'PersonalHoursField',
  Name: 'PersonalHoursField',
  FieldType: 'Text',
  Type: 'Text',
  Filterable: 'FALSE',
  Sortable: 'FALSE',
  ReadOnly: 'TRUE',
}, {
  AllowGridEditing: 'FALSE',
  DisplayName: 'Hours Down',
  RealFieldName: 'HoursDownField',
  Name: 'HoursDownField',
  FieldType: 'Text',
  Type: 'Text',
  Filterable: 'FALSE',
  Sortable: 'FALSE',
  ReadOnly: 'TRUE',
}]

我想以一种更具可读性的方式表示这一点。除DisplayName,RealFieldName和Name外,所有属性都应保持不变。如何在不声明每个对象的整个结构的情况下重新创建此数组?

1 个答案:

答案 0 :(得分:1)

您可以使用spread运算符:

let result = fieldObjects.map(({DisplayName, RealFieldName, Name, ...rest}) => rest);

var fieldObjects = [{
  AllowGridEditing: 'FALSE',
  DisplayName: 'Submit',
  RealFieldName: 'SubmitField',
  Name: 'SubmitField',
  FieldType: 'Text',
  Type: 'Text',
  Filterable: 'FALSE',
  Sortable: 'FALSE',
  ReadOnly: 'TRUE',
}, {
  AllowGridEditing: 'FALSE',
  DisplayName: 'Hours Up',
  RealFieldName: 'HoursUpField',
  Name: 'HoursUpField',
  FieldType: 'Text',
  Type: 'Text',
  Filterable: 'FALSE',
  Sortable: 'FALSE',
  ReadOnly: 'TRUE',
}, {
  AllowGridEditing: 'FALSE',
  DisplayName: 'Personal Hours',
  RealFieldName: 'PersonalHoursField',
  Name: 'PersonalHoursField',
  FieldType: 'Text',
  Type: 'Text',
  Filterable: 'FALSE',
  Sortable: 'FALSE',
  ReadOnly: 'TRUE',
}, {
  AllowGridEditing: 'FALSE',
  DisplayName: 'Hours Down',
  RealFieldName: 'HoursDownField',
  Name: 'HoursDownField',
  FieldType: 'Text',
  Type: 'Text',
  Filterable: 'FALSE',
  Sortable: 'FALSE',
  ReadOnly: 'TRUE',
}]

let result = fieldObjects.map(({DisplayName, RealFieldName, Name, ...rest}) => rest);
console.log(result);