我有带子节点的treenodes,我想用字符串数组过滤它。这是treenodes的结构:
let books = [
{
code: 'CHEM',
key: 1,
children: [
{
code: 'OCHEM',
key: 2,
children: [
{
code: 'AGCHEM',
key: 3,
},
{
code: 'BMCHEM',
key: 4,
},
],
},
],
},
{
code: 'BIO',
key: 9,
children: [
{
code: 'MBIO',
key: 10,
},
],
},
];
并且该数组来自另一个treenode,但仅代码
filters = ['CHEM','OCHEM', 'AGCHEM']
预期的结果是:
let books = [
{
code: 'CHEM',
key: 1,
children: [{
code: 'OCHEM',
key: 2,
children: [{
code: 'AGCHEM',
key: 3
}]
}]
}
];
所以,本质上需要使用我拥有的过滤器代码来过滤treenode。我一直都没有运气尝试过。
filterTree(books: TreeNode[], filters: string[]): TreeNode[] {
const result = books.filter((book) => {
if (book.children) {
book.children = this.filterTree(book.children, filters);
}
return filters.includes(book.code);
});
return result;
}
您的代码按预期工作: