【问题标题】:Add Arrays inside another array in a Class to save the object在类中的另一个数组中添加数组以保存对象
【发布时间】:2020-08-16 20:46:44
【问题描述】:

我有这门课:

 export class Cliente {
  public idCliente?: string;
  public nome?: string;
  public email?: string;
  public imgCliente?: string;
  public dataCadastro?: any;
  public dtUltimoContato?: any;
  public cpfCnpj?: number;
  public identidade?: string;
  public telefone?: string;
  public address?: Address;
  public pesquisa?: string[];
  public sexo?: string;
}

我想获取其中一些属性(nome、cpfCnpj、电话、电子邮件)并创建一个数组并填充“pesquisa”属性。

为此,我使用它来将“nome”转换为数组:

nome.toLowerCase().split(' ', )

我希望在类中创建一些函数,因此例如将对象保存在数据库中时,它已经将字段“pesquisa”保存为包含上述数据的数组。

我该怎么做?

如果有更好的想法,也非常欢迎。

【问题讨论】:

标签: typescript


【解决方案1】:

正如 Lesiac 在评论中提到的,您可以在打字稿中使用 get/set properties。以下是示例代码,您可以根据需要自定义 -

class Cliente {  
  public nome?: string;  
  private _pesquisa!: String[];
  
  get pesquisa(): string[] {
    return this.nome!.split(',');//Used , as separator in this example.
  }

  set pesquisa(newpesquisa: string[]) {
    //Do some calculations for setter
    this._pesquisa = newpesquisa;
  }

  toJSON() {
      return {
        nome:this.nome,
        pesquisa: this.pesquisa
      }
    }
}

使用计算属性的示例测试用例:

let cliente = new Cliente();
cliente.nome = 'Alice,Bob';

console.log(cliente.pesquisa); // ["Alice", "Bob"]
console.log(JSON.stringify(cliente)); //{"nome":"Alice,Bob","pesquisa":["Alice","Bob"]}

注意:使用tsc 编译器目标版本到"es5/above" 以使用此SO thread. 中提到的get/set 属性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 2021-12-23
    • 2021-12-28
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多