function filterTree(tree, key) {
return tree.map(item => {
if (item.type === 'user') {
if (item.title.includes(key)) {
return item;
} else {
return null;
}
} else if (item.type === 'organization' && item.children) {
const filteredChildren = filterTree(item.children, key).filter(Boolean);
if (filteredChildren.length > 0) {
return { ...item, children: filteredChildren };
} else {
return null;
}
}
}).filter(Boolean);
}
const tree = [
{
title: '公司名',
type: 'organization',
children: [
{
title: 'FE',
type: 'organization',
children: [
{ title: 'wells', type: 'user' },
{ title: 'Harrison', type: 'user' },
],
},
{
title: 'joe',
type: 'user',
},
],
},
{
title: '其他',
type: 'organization',
children: [
{ title: 'jason', type: 'user' },
{ title: 'jack', type: 'user' },
],
},
];
const key = 'j';
const newTree = filterTree(tree, key);
console.log(newTree);
console