Разбор дерева категорий в HTML-тег выбора - PullRequest
0 голосов
/ 24 января 2019

У меня есть следующие данные для дерева категорий:

"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": []
            }
        ]
    }
]

Итак, теперь я хочу заполнить поле выбора следующим образом:

Upstate

North

- ребенок N 1

- еще один ребенок 1

- еще один ребенок 2

- активность

здоровье

-Хорошее здоровье

-Плохое здоровье

Итак, как мне проанализировать дерево ввода и заполнить поле выбора этими значениями?Какой-нибудь алгоритм или рекурсивный подход я могу использовать для достижения этой цели?

1 Ответ

0 голосов
/ 24 января 2019

сделать рекурсивную функцию

  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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...