【问题标题】:Angular Typescript map the elements of array to the class object (attributes) or create an object based on array elements?Angular Typescript 将数组的元素映射到类对象(属性)或基于数组元素创建对象?
【发布时间】:2020-10-09 07:32:08
【问题描述】:

我正在使用:

Angular CLI:10.0.6

节点:12.18.2

操作系统:win32 x6

角度:10.0.10

我有一种方法可以从 ag-grid 中获取选定的行。

返回值:

这是一排。现在我有一个对应于这个数组元素的类,即 22 个属性。我想将此数组(行)映射到它的属性。

例如

export class Summary {

  constructor(
    public date: Date,
    public name: string,
    public myNum: string,
    public entity: string,
    // other attributes 
  ) {

  }
}

基本上,这与返回的行具有完全相同的属性(因为该行属于该对象)。

我需要将数组行转换为 Summary 对象,以便可以将其作为 Http 请求发送(Rest API 接受 List 作为请求对象)。

如何做到这一点?

【问题讨论】:

  • 完全控制每个数组中参数的顺序,最简单的方法是一一赋值{par1: arr[0], par2: arr[1], ...}。或者,以正确的顺序构建一个具有属性名称的数组并遍历它们直到最后,收集值数组中等效索引位置的值。我想你只做一次。如果这遍布整个应用程序,那么服务器可能会以正确的顺序向您发送属性名称数组。

标签: arrays angular typescript


【解决方案1】:

我会这样做:

列索引需要始终代表同一个字段

export class Summary {
  
    public date: Date;
    public name: string;
    public myNum: string;
    public entity: string;
    ...

  constructor(args:any[]) {
    this.date = args[0];
    this.name = args[1];
    ...
  }
}

在ts中

const summary = new Summary(row)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2018-12-14
    • 2017-12-17
    • 2021-12-07
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多