首页 > 解决方案 > 将类别树解析为 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

-活动

健康

-身体健康

- 健康状况不佳

那么,如何解析输入树并使用这些值填充选择框?我可以使用任何算法或递归函数方法来实现这一点?

标签: javascripthtmlangularmultidimensional-arrayhtml-select

解决方案


做一个递归函数

  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中看到


推荐阅读