[英]Filter N level nested array of objects based upon multiple properties
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,那么我們需要返回該節點和該 object 的所有父節點。
例如,如果我搜索“你好”,最終的樹應該是:
[
{
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)
這應該適合你。 演示代碼在 stackblitz 中。 在控制台中查看結果。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.