viiii
viiii

Reputation: 1237

How to loop and display object key?

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.

Upvotes: 1

Views: 62

Answers (2)

user13062011
user13062011

Reputation:

Try this

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

Upvotes: 0

traynor
traynor

Reputation: 8667

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}}

Upvotes: 3

Related Questions