使用子对象数组迭代嵌套对象
我正在尝试使用 Angular TS 迭代结构如下的嵌套对象:
{
"stringKey1": {
"child": [
{
"stringKey2": {
"child": []
}
},
{
"stringKey3": {
"child": []
}
},
{
"stringKey4": {
"child": [
{
"stringKey5": {
"child": []
}
},
{
"stringKey6": {
"child": []
}
}
]
}
}
]
}
}
基本上每个“节点”都由一个字符串 Key 和一个对象 {"child" : []} 组成,该对象可以有许多具有相同结构的子级。
我尝试使用管道 *ngFor ,尝试 *ngIf 来检查它是否是一个数组,但我无法使其工作。不可能知道该结构有多深。
基本上尝试了我在互联网上看到的任何东西,但我可能会错过一些东西。
有什么帮助吗?
多谢。
I am trying to iterate using Angular TS over a nested object structured like that:
{
"stringKey1": {
"child": [
{
"stringKey2": {
"child": []
}
},
{
"stringKey3": {
"child": []
}
},
{
"stringKey4": {
"child": [
{
"stringKey5": {
"child": []
}
},
{
"stringKey6": {
"child": []
}
}
]
}
}
]
}
}
Basically each "node" is composed by a string Key and a object {"child" : []} that can have many children with the same structure.
I tried *ngFor with pipe, tried *ngIf to check if it is an array, but I can´t managed to make it work. It´s not possible to know how deep is the structure.
Basically a tried anything I have seen in the internet but I might be missing something.
Any help?
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会避免嵌套对象 for 循环带来的过多模板逻辑。很难阅读和调试。相反,如果可能,请简化 TS 代码中的数据。然后在模板中对其进行操作。
但我们可以利用
| keyvalue
管道使用*ngFor
迭代对象。然后我们使用 ng-template 和 *ngTemplateOutlet 来创建递归。这是一个工作示例: https://stackblitz.com/edit/angular-nested-ngfor-in-table-4nqhve?file=src%2Fapp%2Fapp.component.html
I would avoid excess template logic that comes with nested object for-looping. It's hard to read and debug. Instead, simplify data in TS code if possible. And then manipulate it in template.
But we can make of use
| keyvalue
pipe to iterate over Objects with*ngFor
. We then useng-template
and*ngTemplateOutlet
to create recursion.Here is a working example: https://stackblitz.com/edit/angular-nested-ngfor-in-table-4nqhve?file=src%2Fapp%2Fapp.component.html