I am interested in forming an object using an array and then looping through the keys of that object

I have a custom object with multiple attributes stored in an array.

class Test {

 a1;
 a2;
 a3;
 a4;
 a5;

}

In my project, I have an array that always follows the same order as the attributes of the Test object.

arrayWithValues = [a1,a2,a3,a4,a5];

To simplify the creation process, I am looking to add a static method to the Test class that can generate new instances based on an array of values.

createNewTestObject (param: []) {

... Including a constructor if necessary. 

}

I aim to iterate through each attribute defined in the class and instantiate a new object using the provided array values.

Is this feasible?

Answer №1

The list is devoid of names; solely values can be found within. Each property must have its name explicitly declared for assignment:

function generateNewTestData(param) {
  const data = new TestData;
  data.value1 = param[0];
  data.value2 = param[1];
  data.value3 = param[2];
  data.value4 = param[3];
  data.value5 = param[4];
}

This process could (and probably should) take place within the constructor of the TestData class instead of a separate function, though the methodology remains consistent. While there may exist alternative syntax options that are more concise, none currently allow for iteration with a loop.


I suggest following this structure:

class TestData {
  constructor(
    public value1,
    public value2,
    public value3,
    public value4,
    public value5,
  ) {}
}

Subsequently, utilize spread syntax for invocation:

function generateNewTestData(param) {
  return new TestData(...param);
}

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: An uncaught TypeError has occurred in a TypeScript script using three.js, stating that it is unable to read the 'position' property of

I'm encountering a small issue with initializing the camera position in my three.js project written in TypeScript. The browser console is showing me an error message: Uncaught TypeError: Cannot read property 'position' of undefined. Below is ...

Delay the execution until all promises inside the for loop are resolved in Angular 7 using Typescript

I am currently working on a project using Angular 7. I have a function that contains a promise which saves the result in an array as shown below: appendImage(item){ this.imageCompress.compressFile(item, 50, 50).then( result => { this.compressedI ...

My Angular Router is creating duplicate instances of my route components

I have captured screenshots of the application: https://ibb.co/NmnSPNr and https://ibb.co/C0nwG4D info.component.ts / The Info component is a child component of the Item component, displayed when a specific link is routed to. export class InfoComponent imp ...

Is it possible for me to define TypeScript interfaces to be used in vanilla JavaScript projects within VSCode?

While using the MS VisualCode editor, I am attempting to implement type checking in my Javascript code. I want to maintain the flexibility of Javascript while also benefiting from type checking interfaces and data structures. Based on the vscode documenta ...

The FormData object appears to be blank, even though it was supposed to be populated when attempting to send a PDF file using a multipart FormData POST request in Cypress

I am attempting to send a PDF file as a POST request. The API supports the use of @RequestPart and @RequestParam: @RequestPart("file") MultipartFile file; @RequestParam(value = "document-types", required = false) Set<String> documentTypes; My appro ...

Leveraging the power of react-hook-form in combination with the latest version 6 of @mui

When using MUI v5 date pickers, I utilized the following method to register the input with react-hook-form: <DatePicker ...date picker props renderInput={(params) => { return ( <TextField {...params} ...

Creating circular artwork with PixiJS: A step-by-step guide

I am trying to create a circular image with specific height and width dimensions, but have not found a satisfactory solution. Currently, I can achieve this using a texture, however it is drawn multiple times in the same position. const test = new Graphic ...

Splitting code efficiently using TypeScript and Webpack

Exploring the potential of webpack's code splitting feature to create separate bundles for my TypeScript app has been a priority. After scouring the web for solutions, I stumbled upon a possible lead here: https://github.com/TypeStrong/ts-loader/blob/ ...

The reason why Class-validator doesn't handle fields that lack a decorator in Nest js

After creating a DTO for my endpoint, I encountered an issue where the class-validator stops checking a field if it doesn't have a decorator assigned to it. Even though I need the field to be mandatory and checked, it gets skipped. DTO: import {IsNum ...

What is the best way to generate documentation for the useState function using typedoc?

In my code, I have a documented hook that returns a state along with multiple functions. While the functions are well-documented in typedoc, the status in the final documentation is simply displayed as a boolean without any description. export default func ...

The recursive component is functional exclusively outside of its own scope

I'm facing an issue where my recursive component is not nesting itself properly. The problem arises when I try to use the Recursive component inside another Recursive component. Although the root is correctly inserted into the Recursive component fro ...

Exploring Angular2: Understanding how to retrieve an object with an unknown key

I am trying to showcase a specific value from different objects within a template. The path of the desired value depends on the object being referenced. For example: let obj = { "a": "a", "b": { "1": "1", "2": "READ ME" } } let ...

Step-by-step guide to setting up a TypeScript project on Ubuntu 15 using the

As a newcomer to UBUNTU, I have recently ventured into learning AngularJS2. However, when attempting to install typescript using the command: NPM install -g typescript I encountered the following error message: view image description here ...

Expand the ApiGateProxyEvent category from aws-lambda

Looking to enhance the ApiGateProxyEvent of aws-lambda in d.ts. Initial attempts replaced the entire APIGatewayProxyEvent instead of extending it as intended. declare namespace AWSLambda { interface APIGatewayProxyEvent { body: any; user: any; ...

Can you explain the significance of triple brackets (e.g. {{{ content }}}) in the context of Javascript/Typescript?

As I delve into the code of a fresh project in which I hope to contribute, I have come across numerous methods defined with triple brackets, like so: deinitialize() {{{ this.destroyed = true; $(window).off("resize", this.resize as () => void); ...

Ensure that compiler errors are eliminated for object properties that do not exist

Coming from a JavaScript background, I recently began working with Angular 2 and TypeScript. Below is a snippet of my code: export class AddunitsComponent implements OnInit { public centers:any; constructor(){ this.centers = {}; }} In my view, I h ...

I'm having trouble asynchronously adding a row to a table using the @angular/material:table schematic

Having trouble asynchronously adding rows using the @angular/material:table schematic. Despite calling this.table.renderRows(), the new rows are not displayed correctly. The "works" part is added to the table, reflecting in the paginator, but the asynchron ...

A guide on retrieving TypeScript mongoose/typegoose schema

Here is a defined schema for an account class AccountSchema; Below is the model declaration for the account const AccountClass: Model<AccountSchema & Document>; class Account extends AccountClass; Why isn't this functioning as expected? ...

Steps to simulate a TouchEvent programmatically using TypeScript

Is there a way to manually trigger the touch event in TypeScript? In JavaScript, it was possible but I am struggling to achieve the same in TypeScript. For example: let touchStart: TouchEvent = document.createEvent('TouchEvent'); touchStart.i ...

What is the process of expanding types definitions by incorporating custom types?

I added these custom types to my project. The file structure can be found here. However, these types do not contain certain useful types such as ClientState. I want to include the following enum in those types: enum ClientState { DISCONNECTE ...