首页 > 解决方案 > TS:自定义对象数组的定义

问题描述

这是我的数组定义(可能有问题。我想说这个数组将是自定义对象的数组):

const records: {LicencePlate: string, Description: string, 
SetToUse: string, Depot: string, Active: boolean}[] = [];

然后我想填充它:

  this.grid.gridView.data.forEach(element => {
      records.push(element.LicencePlate, element.Description, element.DateOfStartUse.toLocaleDateString('en-GB'),
      element.Base, element.Active);
    });

我想得到这样的东西 - 对象数组

[{"Johnny", "Actor", "05/03/2000", "Holywood", true}, 
 {"Kirk", "Musician", "01/06/1999", "California", true}, 
 {"Elvis", "Singer", "15/09/1975", "Mississippi", false}]

但我只有一个长数组的单个值:

["Johnny", "Actor", "05/03/2000", "Holywood", true, 
"Kirk", "Musician", "01/06/1999", "California", true, 
"Elvis", "Singer", "15/09/1975", "Mississippi", false]

我在哪里犯了错误?

标签: arraystypescript

解决方案


每次迭代都需要将一个新对象推送到数组中。

就像是:

this.grid.gridView.data.forEach(element => {
  // create object for this row
  const o = {
    LicencePlate: element.LicencePlate,
    Description: element.Description,
    /// other properties and values
  }
  // push that object to array
  records.push(o);
});

推荐阅读