0

Suppose key is 'abc' and value 'true', I should be able to access 'this.abc'; and this should return me 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);    // This should be class variable
                console.info(externalStream[i].value);  // This should be above variable's value

            }
        })
    }
}

2 Answers 2

2

Try this:

Class A {
    public someFun(){

        const obj = this;

        this.external.getData().subscribe((externalStream: Array<someType>) => {
            for(let i:number = 0; i < externalStream.length; i++){
                obj[externalStream[i].key] = externalStream[i].value;
            }
        })
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! This is what I was looking for!, Thank You :)
0

Typescript allows you to create dictionary types (also sometimes called hash maps). This is due to the type-safe nature in Typescript where this JavaScript code is not possible:

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

For a type-safe approach, you would need to know about the existence of the abc property at compile-time, which you often don't. So you do this with a dictionary type:

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

In your case that would be:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.