javascript - 将类别树解析为 HTML 选择标签
问题描述
我有这个类别树输入:
"categories": [
{
"text": "Upstate",
"id": 3,
"category_parent_id": 0,
"children": []
},
{
"text": "North",
"id": 2,
"category_parent_id": 0,
"children": [
{
"text": "Child N 1",
"id": 5,
"category_parent_id": 2,
"children": [
{
"text": "Another Child 1",
"id": 11,
"category_parent_id": 5,
"children": []
},
{
"text": "Another Child 2",
"id": 10,
"category_parent_id": 5,
"children": []
}
]
},
{
"text": "Activity",
"id": 4,
"category_parent_id": 2,
"children": []
}
]
},
{
"text": "Health",
"id": 1,
"category_parent_id": 0,
"children": [
{
"text": "Good Health",
"id": 9,
"category_parent_id": 1,
"children": []
},
{
"text": "Bad Health",
"id": 8,
"category_parent_id": 1,
"children": []
}
]
}
]
所以,现在我想像这样填充我的选择框:
上州
北
-儿童 N 1
——另一个孩子 1
——另一个孩子 2
-活动
健康
-身体健康
- 健康状况不佳
那么,如何解析输入树并使用这些值填充选择框?我可以使用任何算法或递归函数方法来实现这一点?
解决方案
做一个递归函数
flatCategories(data: any[], children: any[], index: number) {
data=data||[];
children.forEach(x => {
data.push({ id: x.id, text: '-'.repeat(index) + x.text });
if (x.children && x.children.length)
this.flatCategories(data, x.children, index + 1)
})
return data
}
你可以使用喜欢
let dataFlat=this.flatCategories([], this.data.categories, 0);
console.log(this.dataflat.map(x => x.text))
如果你想创建一个递归组件很容易(但如果选择不起作用)
@Component({
selector: 'item-line',
template: `
<div *ngFor="let item of children" [style.margin-left]="index+'rem'">
{{item.text}}
<item-line *ngIf="item.children" [children]="item.children" [index]="index+1">
</item-line>
</div>
`,
})
export class HelloComponent {
@Input() children:any[]
@Input() index:number=0;
}
你可以在stackblitz中看到
推荐阅读
- c - 在处理文件之前声明可变数量的变量
- javascript - 在 Firebase 中通过 id 获取特定对象/项目
- .htaccess - htaccess:带有任何 URI 的 URL 不重定向到 https://www
- python - 如何在 wtform validate_ 中获取另一个字段的数据?
- android - Android Studio 的 Javadoc 验证器?
- java - 调试器不在堆栈帧中显示新变量
- html - 除此之外,还有更优雅的方式来格式化表格中的表格吗?我有不同的数字行
- python - 迭代多索引数据帧并将数据存储在新数据帧中的最佳方法
- python - 无法获取字典 For 循环以从正确的列中提取字符串
- jquery - 当前登录的用户属性上的获取/发布/放置方法 - 带有 ajax 请求 jquery 的 ASP.NET Web API 2