ngFor to iterate json sub array with unknown keys

谁说胖子不能爱 提交于 2019-12-10 12:25:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!