Home > OS >  How to store JSON values in an object costructor in TypeScript
How to store JSON values in an object costructor in TypeScript

Time:04-15

I have a JSON file in my project, that containes an array of products specs, and i have an object with a constructor with the same specs, i need to create an array of this object that contains the products from the json file:

I ll write an exemple to be more clear:

this is my json file for exemple:

[
  {
    "id":1,
    "nom": "APPLE IPHONE 13 256GO",
    "description": "some desc ...",
    "prix": 1599.0,
    "quantité": 15,
    "photo": "../Images/iphone-13"
  },
  {
    "id":2,
    "nom": "GALAXY NOTE10",
    "description": "some desc ...",
    "prix": 200.0,
    "quantité": 10,
    "photo": "../Images/galaxy"
  },
  {
    "id":3,
    "nom": "APPLE IPHONE 12 128GO",
    "description": "some desc ...",
    "prix": 1599.0,
    "quantité": 15,
    "photo": "../Images/iphone-12"
  }
]

And, this is my object Class:

export class Product {
  constructor(
    public id: number,
    public name: string,
    public desc: string,
    public price: number,
    public qty: number,
    public imgUrls: string[]
  ) {}
}

i want to create an array of type Product using informations in the JSON file to get something like :

products: Product[] = [
new Product(1,
            "APPLE IPHONE 13 256GO",
            "some desc...",
            1599.0,
            15,
            ["../Images/iphone-13"]),
new Product(2,
            "GALAXY NOTE10",
            "some desc...",
            200.0,
            10,
            ["../Images/galaxy"]),
new Product(3,
            "APPLE IPHONE 12 128GO",
            "some desc ...",
            1599.0,
            15,
            ["../Images/iphone-12"])
];

CodePudding user response:

This works, just make sure the names match

export class Product {
  constructor(
    public id: number,
    public nom: string,
    public description: string,
    public prix: number,
    public quantite: number,
    public photo: string
  ) {}
}

const products:Array<Product> = [
  {
    "id":1,
    "nom": "APPLE IPHONE 13 256GO",
    "description": "some desc ...",
    "prix": 1599.0,
    "quantite": 15,
    "photo": "../Images/iphone-13"
  },
  {
    "id":2,
    "nom": "GALAXY NOTE10",
    "description": "some desc ...",
    "prix": 200.0,
    "quantite": 10,
    "photo": "../Images/galaxy"
  },
  {
    "id":3,
    "nom": "APPLE IPHONE 12 128GO",
    "description": "some desc ...",
    "prix": 1599.0,
    "quantite": 15,
    "photo": "../Images/iphone-12"
  }
];

CodePudding user response:

First read the file from the filesystem and parse it (or alternatively import it). Then map over the array and create and instance of Product for each object in the array. As your imgUrl is an array of strings you will have to check whether the input is an array or not and possibly wrap a single value in the array.

import { readFile } from "fs/promises";

interface IValue {
  id: number;
  nom: string;
  description: string;
  prix: number;
  quantité: number;
  photo: string;
}

async function getValues(): Promise<Array<IValue>> {
  // read file from filesystem
  // TODO: error handling
  const valuesRaw = await readFile("./values.json", { encoding: "utf-8" });
  return JSON.parse(valuesRaw);
}

class Product {
  public id: number;
  public name: string;
  public desc: string;
  public price: number;
  public qty: number;
  public imgUrls: string[];

  constructor(
    id: number,
    name: string,
    desc: string,
    price: number,
    qty: number,
    imgUrls: string[]
  ) {
    this.id = id;
    this.name = name;
    this.desc = desc;
    this.price = price;
    this.qty = qty;
    this.imgUrls = imgUrls;
  }
}

(async () => {
  const values = await getValues();
  const result: Product[] = values.map(
    (prod) =>
      new Product(
        prod.id,
        prod.nom,
        prod.description,
        prod.prix,
        prod.quantité,
        // check wether data is an array and if it's not put the single value in an array
        Array.isArray(prod.photo) ? prod.photo : [prod.photo]
      )
  );
  console.log(result);
})();

Expected output:

[
  Product {
    id: 1,
    name: 'APPLE IPHONE 13 256GO',
    desc: 'some desc ...',
    price: 1599,
    qty: 15,
    imgUrls: [ '../Images/iphone-13' ]
  },
  Product {
    id: 2,
    name: 'GALAXY NOTE10',
    desc: 'some desc ...',
    price: 200,
    qty: 10,
    imgUrls: [ '../Images/galaxy' ]
  },
  Product {
    id: 3,
    name: 'APPLE IPHONE 12 128GO',
    desc: 'some desc ...',
    price: 1599,
    qty: 15,
    imgUrls: [ '../Images/iphone-12' ]
  }
]
  • Related