Converting Array Elements to Class Properties in Typescript

Let's say we have a key 'abc' with the value of 'true'. It should be possible to access 'this.abc' and expect it to return true.

Class A {
    public someFun(){
        this.external.getData().subscribe((externalStream: Array<someType>) => {
            for(let i:number = 0; i < externalStream.length; i++){
                console.info(externalStream[i].key);    // The intention is for this to refer to a class variable
                console.info(externalStream[i].value);  // This value should correspond to the variable above

            }
        })
    }
}

Answer №1

Give this a shot:

Class B {
    public trySome(){

        const data = this;

        this.external.retrieveData().observe((externalStream: Array<someType>) => {
            for(let j:number = 0; j < externalStream.length; j++){
                data[externalStream[j].key] = externalStream[j].value;
            }
        })
    }
}

Answer №2

When using Typescript, you have the ability to create dictionary types, also known as hash maps. This feature is a result of the type-safe nature of Typescript that prevents certain JavaScript code like the following:

var value = {};
value.abc = true;
for (var key in value) {
    console.info(key);
    console.info(value[key]);
}

To ensure type safety, you must be aware of the properties at compile-time, which may not always be the case. This is where a dictionary type comes into play:

let value: { [key: string]: boolean };
value['abc'] = true;
for (var key in value) {
    console.info(key);
    console.info(value[key]);
}

In your specific scenario, it would look something like this:

class A {
    public someFun(){
        this.external.getData().subscribe((externalStream: Array<{ [key: string]: boolean }>) => {
            for(let i:number = 0; i < externalStream.length; i++){
                for(let key in externalStream[i])  {
                    console.info(key);
                    console.info(externalStream[i][key]);
                }
            }
        })
    }
}

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

The parameter type 'NextHandleFunction' does not match the expected type 'PathParams' in the argument

After successfully setting up TypeScript with a basic Express server, I've encountered an issue. import bodyParser from 'body-parser'; import express, { Express } from 'express'; const app: Express = express(); app.use(bodyParser ...

Dealing with Errors - Utilizing Observable.forkJoin with multiple Observable instances in an Angular2 application

One of my Angular applications has two objects, Observable<Object1[]> and Observable<Object2[]>, that call different APIs in the resolver: resolve(): Observable<[Array<Object1>, Array<Object2>]> { const object1 = this.boo ...

Tracking property changes in Angular can help developers easily identify modifications to specific

import { Component ,OnInit} from '@angular/core'; import { QuizService } from './quiz.service'; import { timer } from 'rxjs'; import { take, map } from 'rxjs/operators'; @Component({ selector: 'app-r ...

Receive the most recent information from Angular's service method

I offer a unique service. handler.ts import { Observable,of,Subject } from 'rxjs'; import { PlayerService } from "./../../core/services/player.service"; import { Injectable } from "@angular/core"; import { DeezerService } from "../services/deez ...

Click on Ionic to toggle the label and enable editing

https://i.sstatic.net/NJMWl.png I am looking to implement something similar to the image above. When the edit button is clicked, I want to be able to edit the label (referred to as "A little about you label"). How can this be achieved? <ion-item-divid ...

Guide to utilizing props conditionally in a Material UI TextField component

I am looking to build a comprehensive component using Material UI TextField along with Formik While I have managed all other props, I am facing difficulty in dealing with value and onChange, I have tried using 2 functions for onChange, but find it cumber ...

What is Angular's approach to handling a dynamic and unprocessed JSON object?

When a JSON file is placed under assets, accessing it using something like http://localhost:4200/myapp.com/assets/hello.json will fetch the JSON file directly without any graphical user interface. This indicates that Angular must be able to return a raw JS ...

Encountering a "Cannot POST" error in Angular upon redirection to a callback URL with a SAML response

Currently, I'm implementing SAML authentication in my angular application that will be hosted on AWS. The angular code is stored in a separate project from the webapi where Itfoxtec saml library is being utilized. The flow of communication between my ...

Identifying and organizing scroll-related errors in AngularJS using TypeScript clustering

Attempting to incorporate lazy loading using Clusterize.js in AngularJS TypeScript, but encountering errors. Any expert advice would be greatly appreciated. HTML VIEW <div id="scrollArea" class="clusterize-scroll"> <ul id="contentArea" clas ...

Retrieving Status Text from an Angular 8 Http Service

My application includes a service that sends a POST request to a server: addPerson(person:PersonDTO) :Observable<any> { return this.httpClient.post<any>(this.urlBase + 'Persons', person); } When subscribing to the service in a comp ...

Inquiry on ReactJS conditional rendering concept

Attempting to utilize the <Conditional if={condition}> component in React, which will only render its content if the condition evaluates to true. Referencing the code found on this page, as mentioned in Broda Noel's response to this inquiry. Th ...

Obtaining the Enum key in Angular using the Enum type instead of a string value

Is there a way to retrieve the key of an enum not as a string, but with the enum itself? https://stackblitz.com/edit/typescript-av8rkx enum Widgets { Foo = "this is foo", Bar = "this is bar" } const current = "this is foo" ...

Tips for boosting ViteJs development mode performance

One issue I am facing is the slow server performance during development mode. After starting the server and opening the page in my browser, I have to wait 3–6 minutes for it to load! Initially, ViteJs downloads a small amount of resources, but then the ...

Step-by-step guide on implementing virtual scroll feature with ngFor Directive in Ionic 2

I am working on a project where I need to repeat a card multiple times using ngFor. Since the number of cards will vary each time the page loads, I want to use virtual scrolling to handle any potential overflow. However, I have been struggling to get it ...

inject a dynamic loading icon within the choices of a datalist in an Angular application

<input list="dataUsers" formControlName="user" placeholder="Type the user name" class="form-control form-control-lg" type="text" (ngModelChange)="doSearch($event)"/> <datalist id=&q ...

Tips for including multiple plugins in a next.config.js

I am eager to introduce sass and BEM methodology into our company's project, but I am encountering some challenges with integrating the sass plugin into our existing codebase. Currently, we are utilizing typescript and CSS plugins. const path = requi ...

Guide on converting general objects into a TypeScript class

Having recently started working with Typescript, I have a JSON object that needs to be mapped to a generic interface. However, my initial attempt at creating the interface seems to be incorrect. I need assistance in constructing a generic interface or cl ...

Mobile application built on Ionic 2 featuring Bluetooth Low Energy (BLE) capabilities

I am in the process of developing an Ionic 2 application that displays a list of all accessible Bluetooth devices and establishes connections with them effortlessly. I began by setting up a new Ionic v2 project and adding the BLE plugin to it. Your help w ...

Tips for creating type-safe assertion functions in TypeScript

In TypeScript 3.7, a new feature allows the writing of "assertion functions." One example is shown below: export type TOfferAttrName = keyof typeof offerAttrMap; export const assertIsOfferAttrName = (name: string): asserts name is TOfferAttrName => { ...

Are there certain RxJS operators that seem to be missing in your Angular2 CLI project? Wondering what steps to

Currently, I am diving into the world of RxJS and experimenting with various operators and combinations that pique my interest. I am studying from resources like this and this. In my Angular2 rc4 CLI project, using Typescript, I am encountering an issue ...