0

I have this class:

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

I want to get some of these attributes(nome, cpfCnpj, telefone, email) and create an array and populate the "pesquisa" attribute.

For that, I am using this to transform "nome" into an array:

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

I wish to create some function inside the class, so when saving the object in database for example, it already saves the field "pesquisa" as an array with the mentioned data.

How would I do that?

If there is a better idea, it is very welcome also.

DValdir Martins
  • 159
  • 4
  • 14
  • 2
    I would go with a get accessor: https://www.typescriptlang.org/docs/handbook/classes.html#accessors – Lesiak Aug 16 '20 at 21:27

1 Answers1

1

As mentioned by Lesiac in the comment, you could use the get/set properties in typescript. Below is the sample code which you can customize according to your need -

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
      }
    }
}

Sample test case to use the calculated property:

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"]}

Note: Use the tsc compiler target version to "es5/above" to use the get/set properties as mentioned in this SO thread.

MBB
  • 1,635
  • 3
  • 9
  • 19