0

I get a specific user from my dummy json file and looks like this:

"id": "2",
"name": "Marios Manolakeris",
"skills": [
     {
         "skill_1": "Machine Learning",
         "skill_2": "AI",
         "skill_3": "C++"
     }
]

I need to iterate through skills, even if theoretically i don't know the key values skill_1, skill_2, skill_3.

So, a solution is to do this:

<div *ngFor="let skill of user.skills">{{skill.skill_1}}, {{skill.skill_2}}, {{skill.skill_3}}</div>

but, I want to iterate through user.skills automatically.

Is there any way? Thanks!

1 Answer 1

3

You can use Object.keys when keys are unknown like below:

<div *ngFor="let skill of skills">
  <div *ngFor="let item of skill | keyvalue">
        {{item.value}}
  </div>
</div>

OR 6.1+ onwards you can use keyvaluepipe as below:

<div *ngFor="let skill of skills">
  <div *ngFor="let item of objectKeys(skill)">
        {{skill[item]}}
  </div>
</div>

In .ts

objectKeys = Object.keys;
public user={"id": "2",
    "name": "Marios Manolakeris",
    "skills": [
        {
            "skill_1": "Machine Learning",
            "skill_2": "AI",
            "skill_3": "C++"
        }
    ]
}
skills:any;
constructor(){
  this.skills = this.user.skills;
}

Stackblitz here: https://stackblitz.com/edit/angular-fst8lm-bjg5hu

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

2 Comments

Hey, thanks for the answer. I am getting this error though Cannot read property 'keys' of undefined
Didn't notice skills is an array. Updated my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.