Home > Net >  Typescript: How should I convert a json file to a class instance?
Typescript: How should I convert a json file to a class instance?

Time:09-09

my NoSQL returns the following output:

{
   "id": "1234fc8-33aa-4a39-9625-b435479e6328",
   "name": "02_Aug 10:00",
   "country": "UK"
}

I created Person class and a PersonDto interface in my code base as follow:

interface PersonDto {
    id: string;
    name: string;
    country: string;
    property4: string;
    ...
    ...
    property20: string
}

class Person {
  private id: string;
  private name: string;
  private country: string;
  private property4: string;
  ...
  ...
  private property20: string;

   constructor(personDto: PersonDto) {
       /* 
       How can I convert the json properties to class properties
       without writing them one by one? Is there a way to 
       dynamically iterate over the properties?

       Or maybe there is a better way to get the same outcome?
       */
       this.id = personDto.id;
       this.name = personDto.name;
       this.country = personDto.country;
       this.property4 = personDto.property4;
       ...
       ...
       this.property20 = personDto.property20;
    }
}

What is the best practice in this case?

How should I convert a json file to a class instance in TS?

CodePudding user response:

You should describe the type of PersonDto:

interface PersonDto {
  id: string;
  name: string;
  country: string;
}

class Person {
  private id: string;
  private name: string;
  private country: string;

  constructor(personDto: PersonDto) {
    this.id = personDto.id;
    this.name = personDto.name;
    this.country = personDto.country;
  }
}

const data = {
  "id": "1234fc8-33aa-4a39-9625-b435479e6328",
  "name": "02_Aug 10:00",
  "country": "UK"
};

const person = new Person(data);
console.log(person);

In a case you a sure that all PersonDto properties are string - you can simplify the type description: type PersonDto = { [key: string]: string };

CodePudding user response:

Try Object.assign to not have to type every property.

interface PersonDto {
  id: string;
  name: string;
  country: string;
}

class Person {
  private id: string;
  private name: string;
  private country: string;

  constructor(personDto: PersonDto) {
    Object.assign(this, personDto);
  }
}

const data = {
  id: "1234fc8-33aa-4a39-9625-b435479e6328",
  name: "02_Aug 10:00",
  country: "UK"
};

const person = new Person(data);
console.log(person);
  • Related