Creating a variable name dynamically using Typescript

I am looking to efficiently create multiple instances of variables and assign values in a single statement, an example of which is shown below.

this.myList1[data.id] = data.id + "-" + data.desc;
this.myList2[data.id] = data.id + "-" + data.desc;
this.myList3[data.id] = data.id + "-" + data.desc;
this.myList4[data.id] = data.id + "-" + data.desc;
this.myList5[data.id] = data.id + "-" + data.desc;
this.myList6[data.id] = data.id + "-" + data.desc;

Could someone provide guidance on the best approach to achieve this using Typescript?

Answer №1

Implement template string literals and bracket notation syntax using this:

myList.forEach((data: object, index: number) => {
    this[`myList${index + 1}`][data.id] = `${data.id}-${data.desc}`;
});

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

Effortlessly adding custom classes in Angular 2 with a breeze

Imagine having a growing Angular2 typescript solution with numerous small classes and objects. Following the best practice, each class is placed in its own file. However, manipulating these objects leads to long lists of imports like: import {Object1} f ...

Tips on searching for an entry in a database with TypeScript union types when the type is either a string or an array of strings

When calling the sendEmail method, emails can be sent to either a single user or multiple users (with the variable type string | string[]). I'm trying to find a more efficient and cleaner way to distinguish between the two in order to search for them ...

Unexpected expression after upgrading to TypeScript 3.7.2 was encountered, file expected.ts(1109)

After updating TypeScript from version 3.6.x to 3.7.2, I started using optional chaining in my code. However, I encountered a peculiar error. Error message: Expression expected.ts(1109) This error appeared in both my (vim, VSCode) IDE, even though the ...

Issue with AWS SDK client-S3 upload: Chrome freezes after reaching 8 GB upload limit

Whenever I try to upload a 17 GB file from my browser, Chrome crashes after reaching 8 GB due to memory exhaustion. import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'; import { Progress, Upload } from "@aws-sdk/lib-storage& ...

What distinguishes ReadonlyArray from the declaration "readonly arr: T[]"?

Check out this unique playground. interface Feature { readonly name: string; } // <Test> // This is OK interface Foo1 { readonly arr: ReadonlyArray<Feature>; } function save1(foo: Foo1) { console.log(foo); } // </Test> // <Tes ...

Unit testing Angular components can often uncover errors that would otherwise go unnoticed in production. One common

I need assistance writing a simple test in Angular using Shallow render. In my HTML template, I am utilizing the Async pipe to display an observable. However, I keep encountering the following error: Error: InvalidPipeArgument: '() => this.referenc ...

Converting types to "any" and encountering the error message "There are two distinct types with the same name, but they are not related."

I am encountering some challenges while trying to use an NPM module that I developed along with its Typescript typings in another application. To simplify the examples, I will omit properties that are not relevant to the issue at hand. Within my module&ap ...

Different categories of "areas" found in TypeScript within Visual Studio 2013

In C#, we often use "regions," but unfortunately that feature is missing in TypeScript. Is there a way to group code sections in TypeScript? I came across this article on Stack Overflow discussing the absence of regions in TypeScript. I'm curious if ...

Allow TypeScript function parameters to accept multiple elements from an enumeration

Enumerating my options. export enum Selection { CHOICE_ONE = 'one', CHOICE_TWO = 'two', CHOICE_THREE = 'three', CHOICE_FOUR = 'four', } I am looking to design a function that accepts an array, but re ...

Encountering ReferenceError when attempting to declare a variable in TypeScript from an external file because it is not defined

Below is the typescript file in question: module someModule { declare var servicePort: string; export class someClass{ constructor(){ servicePort = servicePort || ""; //ERROR= 'ReferenceError: servicePort is not defined' } I also attempted t ...

Tips for resolving the error message "TypeError: Converting circular structure to JSON"

I had a straightforward query where I needed to select all from the aliases table. Everything was working fine until I ran npm update. TypeError: Converting circular structure to JSON public async fetchAliases(req: Request, res: Response): Promise< ...

Vue - Troubleshooting why components are not re-rendering after data updates with a method

Check out this simple vue component I created: <template> <div class="incrementor"> <p v-text="counter"></p> <button v-on:click="increment()">Increment</button> </div> </template> <script lan ...

Error: Couldn't locate Next.js - TypeScript module

I encountered an error with the image, but I am unsure of the reason behind it. Additionally, the directory is included in the second image. https://i.sstatic.net/knUzH.png import Link from 'next/link'; import { useState } from 'react' ...

Generating a new object from a TypeScript class using JavaScript

Currently, I am facing an issue while attempting to call a JavaScript class from TypeScript as the compiler (VS) seems to be having some trouble. The particular class in question is InfoBox, but unfortunately, I have not been able to locate a TypeScript d ...

Is it advisable to incorporate 'use server' into every function that retrieves confidential information within server components in Next.js?

By default, server components are enabled in Next.js 13. I'm contemplating whether I should wrap each fetch call in a separate function and include 'use server' to conceal the function's code or if it's acceptable to directly use f ...

Angular sets the required property only when the button is clicked

Is there a way to make a field required in Angular only when a button is clicked? Currently, the error message appears even before the user interacts with the field. I would like the error message "folder name is required" to only appear when the user cli ...

Error encountered when referencing prop on textarea: 'There is no suitable overload for this call'

I've been referring to the documentation in order to set a reference using the useRef hook, with the goal of being able to programmatically clear an input field. However, when I add ref as a prop to a textarea, it triggers a lint error saying that no ...

Using Phoenix Channels and Sockets in an Angular 2 application: A comprehensive guide

My backend is built with Elixir / Phoenix and my frontend is built with Angular 2 (Typescript, Brunch.io for building, ES6). I'm eager to start using Phoenix Channels but I'm struggling to integrate the Phoenix Javascript Client into my frontend. ...

Apply a dynamic function to assign a background color to a specific class

Currently, I have a function called getBackground(items) that returns a background color from a JSON file list. Within my application, there is a component that automatically adds a class name (.item-radio-checked) when a user clicks on an item in the list ...

Angular 4's OrderBy Directive for Sorting Results

I've been working on implementing a sorting pipe based on the code provided in this resource: The issue I'm facing revolves around handling undefined values within my data. The sorting pipe functions correctly when there are no undefined values ...