0

I have an api which will return the map response like .

{thomas: 3, test70: 2, tim: 2, elin: 2, sumeet12: 1}

I want to iterate in angular but unfortunately i got error while trying this.

Error Got ::

This expression is not callable. Type 'Number' has no call signatures.ts(2349)

  this.testObject.forEach((value: number, key: string) => {
    console.log(key, value);
});

Iterating over Typescript Map

But i am able to iterate in the html using below code..

In html

  <div *ngFor="let item of testObject | keyvalue: originalOrder; let i=index">
    <span *ngIf="i<3">
      Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>

    </span>   
  </div>

In .ts file

testObject: { [key: string]: number };
showresult: any;

  getQuizResult(id){
    this.service.getResult(id).subscribe((stndrdResp: Response) => {
      this.showresult = stndrdResp.obj; // this will return a object
      this.testObject = this.showresult; // assigning the key value response to testObject
      });
  }

Basically i want to iterate the backend api response inside the getQuizResult so that i can perform some action. Appreciate your valuable suggestion.

2
  • Have you checked: stackoverflow.com/questions/45605257/… ? Commented Apr 10, 2020 at 7:54
  • @eko yes using this i am able to retrieve the keys but not the corresponding values. Could you please guide me how to get the corresponding value Commented Apr 10, 2020 at 8:42

2 Answers 2

0

I think this is what you are looking for: https://stackoverflow.com/a/24440475/12193298

A comment; in one of your code above you have key: string in the second parameter, but in the forEach callback the second one is the index, which always is a number. So that should be looking like this:

this.testObject.forEach((value: number, index: number) => {
    console.log(index, value);
});
Sign up to request clarification or add additional context in comments.

Comments

0

Because testObject is a plain object,not a Map instance.You need to create a map object or array.

const res = {thomas: 3, test70: 2, tim: 2, elin: 2, sumeet12: 1};
var arr = Object.entries(res);//[[ "thomas", 3 ]...]
var map = new Map(arr);//use arr or create a map

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.