Storing JSON data in an object constructor in TypeScript: A simple guide

REVISION OF MY INQUIRY

I possess a json file titled products.json which holds a collection of products along with their id, name, quantity, description, and image URLs associated with each product. Here is an illustration of the JSON file:

[
  {
    "id":1,
    "name": "APPLE IPHONE 13 256GB",
    "desc": "some description ...",
    "price": 1599.0,
    "qty": 15,
    "imgUrls": "../Images/iphone-13"
  },
  {
    "id":2,
    "name": "GALAXY NOTE10",
    "desc": "some description ...",
    "price": 200.0,
    "qty": 10,
    "imgUrls": "../Images/galaxy"
  },
  {
    "id":3,
    "name": "APPLE IPHONE 12 128GB",
    "desc": "some description ...",
    "price": 1599.0,
    "qty": 15,
    "imgUrls": "../Images/iphone-12"
  }
]

Furthermore, I have the Product object outlined below:

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

My objective is to establish an array of type Product, encompassing all the products imported from the json file.

Although I am aware that creating the products manually would resemble this:

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

My aspiration is to generate this object utilizing the json file.

I deeply appreciate your assistance.

If my explanation is unclear, please feel free to mention that in the comments so I can refine my inquiry.

Answer №1

Ensure the names are matching for this to function correctly

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

Answer №2

To start, you need to read the file from the filesystem and then parse it. Next, loop through the array and create an instance of the Product class for each object in the array. Since the imgUrl property is an array of strings, you should check if the input is an array and wrap a single value in an array if necessary.

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 result:

[
  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' ]
  }
]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an [ERROR] IndexError when attempting to retrieve the InstanceId from the RunInstance cloudtrail json log within a lambda function

Encountering the [ERROR] IndexError: list index out of range in lambda when attempting to retrieve InstanceId from RunInstance cloudtrail json log: [ERROR] IndexError: list index out of range Traceback (most recent call last): Is there a solution for fetc ...

What is the best method for extracting string values from a JavaScript object?

I am working with JavaScript objects that look like this: {["186,2017"]} My goal is to extract and display only the values: 186, 2017 Initially, I attempted to use JSON.stringify thinking it was a JSON: console.log(JSON.stringify(data)); However, thi ...

Using onDoubleClick with MUI TextField: A Quick Guide

Whenever the user double clicks the input field, I would like to automatically select the text. I have created a function for this specific action: export const selectText = ( event: React.MouseEvent<HTMLInputElement | HTMLTextAreaElement, MouseEvent& ...

The call does not match any overloads in Vue when using TypeScript

What is the reason behind the occurrence of the error in the ID part of the query? This call does not have a matching overload. <template> <swiper-slide slot="list" v-for="(list, index) in list.banner" :key=" ...

JavaScript Regular Expression that identifies commas enclosed within quotation marks

I am attempting to parse a text-based log file in the following format: type: 'click', category: 'REFRESH_DOOR', desc: 'clicked refresh from door 0124', site: 'mysite', pathname: '/load_areas/all/doors&apos ...

Tips for integrating yarn add/npm install with monorepositories

I am attempting to retrieve a node package from a private monorepo on GitHub, structured similarly to this: monorepoProject --- subProjectA --- subProjectB Both subProjectA and subProjectB are TypeScript projects, following the layout depicted below: ...

The issue with Angular's "let-col" directive is that it does not successfully pass along every property

Extra fields have been implemented to aid in processing tasks. Below is how the columns array is defined: this.columns = [ {field: 'vin', header: 'Vin', isMultiRowColumn: true }, {field: 'year', header: ' ...

Guide to highlighting input field text using Angular

I've set up an angular page that includes an input field within its template. My goal is to highlight the text in the input field when a specific function is triggered. When I refer to "highlighting the text," I mean (check out the image below) https ...

Implementing automatic selection for MUI toggle buttons with dynamic data

By default, I needed to set the first toggle button as selected import * as React from "react"; import { Typography, ToggleButton, ToggleButtonGroup } from "@mui/material"; export default function ToggleButtons() { const dat ...

Tips for successfully sending dual Subjects/Actions flows as HTTP Parameters in a GET call to retrieve a solo object or an array of objects in Angular with the help of RxJS

GOAL: My objective is to retrieve a single object and/or a range of objects from the backend service by utilizing RxJS and passing user inputs as HTTP parameters. For instance, I am leveraging declarative RxJS and have two Subjects (Action streams) to capt ...

Using PHP to access a property using json_decode

Hello, I am attempting to access certain properties using json_decode, but I am encountering issues. Specifically, I am interested in retrieving the values for userRating and pressRating properties. $result_json = json_decode($result, true); echo $result_j ...

To enable the "Select All" functionality in ag-grid's infinite scrolling feature in Angular 4, utilize the header check box

Is there a way to add a checkbox in the header of ag-grid for selecting all options when using an infinite row model? It seems that the headerCheckboxSelection=true feature is not supported in this model. Are there any alternative methods to include a che ...

What is the best way to make an AJAX request to retrieve data from a database in JSP using Extjs?

Currently, I am utilizing the Extjs framework and have created a servlet to retrieve data from a database. Once the data is retrieved, it is stored in a list and then converted into a JSON array. I am now looking to incorporate this data into a JSP page us ...

Creating JavaScript classes based on JSON schemas

I have a JSON file containing information and data related to my work, presented in the following format: { "Employees":[ { "id": 1, "fullName": "Test Test" } ], "Infos":[ { "id": 1, ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...

Utilizing operators for whereJsonContains in Laravel

I have a JSON column called "experience" in my database. It contains an array of objects structured like this: [ { ... "years": 1 }, { ... "years": 2 } ] I am looking to retrieve users with experience years greater than or equal t ...

I am having trouble getting my angular image to switch using angular animations

I am attempting to implement image swapping using Angular animations based on a 10-second timer. However, the swap is not occurring and I have been troubleshooting without success. The goal is for the images to change when the timer reaches 5 seconds, but ...

Retrieve the part of a displayed element

Presently, I am developing a modal system using React. A button is located in the sidebar and the modal is represented as a div within the body. In the render function of the main component of my application, two components are being rendered: MyModal M ...

Issue with CakePHP 3: The $this->set method is not returning any response data following a POST

I'm facing an issue where I am unable to retrieve a response from my controller to my view files. Even though I have confirmed that the controller contains the correct data by using echo for verification, it results in an error related to header emiss ...

What is the most efficient way to extract JSON data from a list and transform it into columns in Python?

I have received JSON data from Amazon, including various sales metrics and information. After using json_normalize to convert the data into a dataframe, I encountered an error while attempting to flatten the nested list in one of the columns. Here is a sni ...