Home > Net >  How to loop and display object key?
How to loop and display object key?

Time:02-04

I have an object as following below:

scores = {"grade1":
               {"math":"120","english":"100"},
           "grade2":
               {"math":"50","english":"50"},
           "grade3":
                {"math":"90","english":"70"}
          }

I want to display object key with *ngFor to look like this:

Field: grade1 
Field: grade2 
Field: grade3

I tried using Object.keys(scores) but it doesn't work.

CodePudding user response:

To loop object keys, transform object to key value pairs with KeyValuePipe:

<div *ngFor="let item of scores | keyvalue">
Field: {{item.key}}

<br>
full object: {{item.key}}:{{item.value | json}}

</div>

and you can get object values via {{item.value}}

CodePudding user response:

Try this

for (let grade in scores) {
  console.log(`Field: ${grade}`);
}
  • Related