问题
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:
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
来源:https://stackoverflow.com/questions/52462077/ngfor-to-iterate-json-sub-array-with-unknown-keys