1

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.

9
  • typescriptlang.org/play?#code/… it does work Commented Feb 3, 2023 at 8:56
  • Does this answer your question? Get array of object's keys Commented Feb 3, 2023 at 9:00
  • yes, but if i want them as an index key and loop, it doesn't work. Commented Feb 3, 2023 at 9:05
  • But you want to loop it on html using *ngFor, correct? Commented Feb 3, 2023 at 9:06
  • @viiii Ah my apologies, I didn't know what ngFor was. Commented Feb 3, 2023 at 9:08

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

Try this

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

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.