下面是我们要处理的数据,简写:
let arr = [
{
title: '你好吗?',
children: [
{
title: '很好啊',
children: null
},
{
title: '是吗',
children: null
}
]
},
{
title: '卡卡卡',
children: [
{
title: '非常好芬',
children: null
}
]
},
{
title: '第三方的',
children: null
}
];
再搜索框输入 好 字时,希望树形结构中带有 好 字的项显示,即使父节点没有 好 字,但子节点含有,父节点仍要返回;代码实现如下:
const rebuildData=(value, arr) => {
let newarr = [];
arr.forEach(element => {
if (element.children && element.children.length) {
const ab = rebuildData(value,element.children);
const obj = {
...element,
children: ab
};
if (ab && ab.length) {
newarr.push(obj);
}
} else {
if (element.title.indexOf(value) > -1) {
newarr.push(element);
}
}
});
return newarr;
};
console.log(rebuildData( '好', arr));
输出如下图:
根据大家提的无法搜索父节点进行了优化:
const rebuildData = (value, arr) => {
let newarr = [];
arr.forEach(element => {
if (element.title.indexOf(value) > -1) {
newarr.push(element);
} else {
if (element.children && element.children.length > 0) {
const ab = rebuildData(value, element.children);
const obj = {
...element,
children: ab
};
if (ab && ab.length>0) {
newarr.push(obj);
}
}
}
});
return newarr;
};
根据大家在评论里提的匹配到父节点,children全部匹配到bug进行优化,最终版:
const rebuildData = (value, arr) => {
if (!arr) {
return []
}
let newarr = [];
arr.forEach(element => {
if (element.title.indexOf(value) > -1) {
const ab = rebuildData(value, element.children);
const obj = {
...element,
children: ab
}
newarr.push(obj);
} else {
if (element.children && element.children.length > 0) {
const ab = rebuildData(value, element.children);
const obj = {
...element,
children: ab
};
if (ab && ab.length > 0) {
newarr.push(obj);
}
}
}
});
return newarr;
};
console.log(rebuildData('好', arr));