Creating an array of custom objects in Typescript involves declaring a class that represents the custom

module NamespaceX{
    interface Serializable<T> {
        deserialize(input: Object): T;
    }

    export class CustomClass implements Serializable<CustomClass>{
        private property1: number;
        private property2:string;
        constructor(val1?:number, val2?:string){
            this.property1 = val1;
            this.property2 = val2;
        }

        deserialize(jsonData){
            if (!(Array.isArray(jsonData))) {
                this.Index = jsonData.index;
                this.HeaderName = jsonData.headerName;
                this.SortName = jsonData.sortName;
                this.AllowSorting = jsonData.allowSorting;
                return this;
            }
            else {
                //Code this section to create a list
            }
        }
    }
}

var jsonDataArray = [{ property1: 1, property2: "Test1"}, { property1: 2, property2: "Test2" }];

var collection:Array<NamespaceX.CustomClass> = new NamespaceX.CustomClass().deserialize(jsonDataArray);

I encountered the following error during compilation while using 'collection':

Type 'CustomClass' is not assignable to type 'CustomClass[]'. Property 'length' is missing in type 'CustomClass'.

How can I convert the JSON array of objects (jsonDataArray) into a list?

Answer №1

Constructors are meant for initializing objects in a class, so there's no need for a separate function to do that.

A better approach would be to iterate through the jsonDatas array and instantiate a new class instance for each item.

You can achieve this easily using a map function.

module NameSpacens{

    export class Class1 {

        constructor(private prop1?:number, private prop2?:string){

        }


    }
}

var jsonDatas = [{ prop1: 1, prop2: "Test1"}, { prop1: 2, prop2: "Test2" }];

var coll:Array<NameSpacens.Class1> = jsonDatas.map((data) => new NameSpacens.Class1(data.prop1, data.prop2));

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

"Error: The method setValue is not found in the AbstractControl type" when trying to clear form in Angular 2

Here is the template code: <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" novalidate="novalidate"> <textarea [ngClass]="{ 'error': comment }" [formControl]="form.controls['comment']" ...

"Troubleshooting: Why is the 'RectAreaLightHelper' not moving correctly in React-three-fiber

Issue Overview: I have noticed that the rectAreaLight behaves differently compared to other light helpers in my project. Despite using the "useHelper" function and placing it in the "three/examples" folder, the position of the rectAreaLight does not change ...

Tips for utilizing the <base> element in HTML5 for selective anchor tags

I only have one base tag in the head section of my HTML document, and there are two anchor tags with different URLs as shown below: <!DOCTYPE html> <html lang="en"> <head> <base href="https://www.youtube.com"/> </head> &l ...

Accessing a component's function from an HTML view in a Vue application

I seem to be stuck in a tricky situation with Vue logic. I have a "list" component that retrieves results from an ajax call. The issue arises when I try to incorporate a search field. Here is what I currently have: search.vue <template> <div> ...

Is there a way to incorporate logic into my Angular routes?

I am looking to secure certain routes within 'case' sections based on the dependency of $scope variables (whether forms are valid or not). var loginForm = angular.module('loginForm',[ 'ngRoute', 'stepsControllers&apo ...

I seem to be having trouble locating the correct file location

Apologies for the simplicity of my question. I've been struggling to include the find.js file in my articles.js file. Despite trying multiple variations, I can't seem to get the pathname right and haven't found a solution online. Can someon ...

Tips for ensuring the security of your code in node.js

Here is a snippet from my app.js that deals with managing connections: var connections = []; function removeConnection(res) { var i = connections.indexOf(res); if (i !== -1) { connections.splice(i, 1); } } I make a call to removeConn ...

Combining Vue and Laravel: Efficiently retrieve API data stored as an array within a tuple

I am facing an issue with setting data from an API into an array in vue.js. The data obtained is in JSON format from the API. Could you please guide me on the syntax for this? {"id":1613, "name_org":"US company", "picture":"default.jpg", "headerpic":"no- ...

Failure to retrieve fax API data using Twilio's Node.js HTTP requests

Looking to implement fax receiving using Twilio API. This is an excerpt from my index.js file: // const http = require('http'); const express = require('express'); const bodyParser = require('body-parser'); c ...

What is the best way to implement the 'setInterval' function in this code to effortlessly fetch forms or data on my webpage without any need for manual refresh?

I am using ajax and javascript to fetch a modal on another page or in a separate browser. While I am able to retrieve the modal, I require the page to refresh before displaying the modal. I have come across suggestions to use the setInterval function but I ...

Exploring Next.js Font Styling and Utilizing CSS Variables

I'm attempting to implement the "next" method for adding fonts, but I find the process described quite complex just to preload a font. I experimented with exporting a function to create the font and then using a variable tag to generate a CSS variabl ...

Troublesome code with Ajax, Jquery, and PHP is causing issues

I've been trying to send an array from php to js using ajax, but for some reason it's not working no matter what I try. I'm convinced it must be a simple fix, but I seem to have exhausted all my options. <!doctype html> <html lang= ...

Unable to retrieve the image

When trying to fetch an image, I encountered the following error: Failed to load resource: the server responded with a status of 404 (Not Found) TopBar.jsx import { useContext } from "react"; import { Link } from "react-router-dom"; ...

I need assistance with using the angular-oauth2-oidc library to retrieve data from an asynchronous storage provider and then pass it to a synchronous storage implementation

Typically, the angular-oauth2-oidc library saves tokens in session storage by default. While you can provide your own storage provider through the OAuthStorage class, it requires a storage provider that can retrieve data synchronously. I am developing a ...

Protractor is able to achieve successful test results without actually executing the tests

SYMPTOMS When running Protractor, the tests pass successfully, but the pages do not load. Instead, they appear blank with "data:text/html" in the address bar (refer to the screenshot). Although the tests show as passed, there are 0 assertions being made. ...

Performing synchronous POST requests to manipulate data in a SQL database using AJAX

My goal is to send synchronous calls to a page that will handle the SQL insertion of words I am posting. However, due to the large number of chunks and the synchronous nature of SQL, I want each AJAX call to be processed one after another. for (chunk = 1; ...

Initial React render fails to retrieve API data

I've encountered an issue during development where the page loads before the API data is sent. I attempted to use asynchronous functions, but it didn't resolve the problem as expected. I suspect that my approach may be incorrect. Here's a sn ...

Ways to determine if the property of a document has been altered?

Currently, I am in the process of writing tests for an Express CRUD application. The specific route I am focused on is the account recovery route. This route accepts POST requests with an email included in the body. Essentially, the application will search ...

Search through the JSON data, identify similar values, and save them in a collection

Struggling to find a way to limit the output of my comparison between attribute values in an object, I am only looking for one output per ID. Any suggestions? //example JSON var obj1 = { "Summary" : [ { "ID" : "1234", "Name" : "Joh ...

In React, I am currently working on implementing a feature that will allow the scene camera to move as the user scrolls

I'm currently working on incorporating a feature to enable movement of the scene camera when scrolling in React. However, as I am relatively new to using this library, I am unsure which implementation approach would be most suitable for achieving this ...