根据多个属性过滤N级嵌套的对象数组

时间:2020-07-17 09:31:50

标签: javascript angular lodash

data = [
    {
      name: "Parent Level 1",
      questions: [
        {
          name: "question 1"
        }
      ],
      children: [
        {
          name: "Child 1 - P1",
          questions: [
            {
              name: "ability to code"
            },
            {
              name: "ability to do something"
            }
          ],
          children: [
            {
              name: "Child -2 P1",
              questions: [
                {
                  name: "figure out"
                }
              ]
            }
          ]
        }
      ]
    },
    {
      name : 'Parent Level 2',
      questions : [
        {name : 'question 1 P-2'}
      ]
    },
    {
      name : 'Parent Level 3',
      children: [
        {
          name : 'Child Level -1 P-3',
          children: [
          {
             name : 'Child Level 2- P-3',
             questions : [
              {
       name : 'Question level 2
              }
             ]
           }
          ]
          questions: [
            {name : 'hello there'}
          ]
        }
      ]
    }
  ];

问题:

我需要对问题进行关键字搜索,如果在一个节点上发现了一个问题-假设3,那么我们需要返回该节点和该对象的所有父节点。

例如,如果我搜索“ hello there”,则最后一棵树应为:

[
    {
      name : 'Parent Level 3',
      children: [
        {
          name : 'Child Level -1 P-3',
          children: [
          {
             name : 'Child Level 2- P-3',
             questions : []
           }
          ]
          questions: [
            {name : 'hello there'}
          ]
        }
      ]
    }
  ];

我们可以在任何节点上有孩子或问题[]。

我能够找到与搜索字符串匹配的问题,但是我无法从树中删除不需要的节点。这是该代码:

searchNode (data) {
    for (let d of data) {
      this.search(d)
    }
 }

 search(data) {
    let search = 'ability'
    if(!!data.questions && data.questions.length > 0) {
      data.questions = data.questions.filter((question) => {
        return question.name.includes(search)
      })
    }
    if(data.children && data.children.length > 0) {
      searchNode(data.children)
    }
  }

search(data)

1 个答案:

答案 0 :(得分:0)

这应该为您工作。演示代码在stackblitz中。在控制台中检查结果。

Stackblitz demo

searchString = 'hello';
filteredData = [];

ngOnInit(): void {
    this.filteredData = [];
    this.data.forEach(node => {
        if (this.checkQtn(node)) {
            this.filteredData.push(node);
        }
    });
    console.log(this.filteredData);
}

checkQtn(node): Boolean {
    let response: Boolean = false;
    if (node.questions) {
        let qtns = [];
        qtns = node.questions;
        qtns.forEach(el => {
            const eachQtn: string = el.name;
            if (eachQtn.includes(this.searchString)) {
                response = true;
            }
        });
    }
    if (!response && node.children) {
        for (let i = 0; i < node.children.length && !response; i++) {
            response = this.checkQtn(node.children[i]);
        }
    }
    return response;
}