我在分层数据结构中有一个对象数组。我需要检查是否有任何父节点或子节点包含搜索字符串。我能够过滤数组,但我只想更新matchFound属性,而不是在树数据上应用过滤器。
预期结果:如果找到匹配,则所有父节点和子节点的matchFound属性应为真,否则为false。
treeData = [{
name: 'Infiniti',
matchFound: null,
children: [{
name: 'G50',
matchFound: null,
children: [{
name: 'Pure AWD',
matchFound: null,
},
{
name: 'Luxe',
matchFound: null,
},
],
},
{
name: 'QX50',
matchFound: null,
children: [{
name: 'Pure AWD',
matchFound: null,
},
{
name: 'Luxe',
matchFound: null,
},
],
},
],
},
{
name: 'BMW',
matchFound: null,
children: [{
name: '2 Series',
matchFound: null,
children: [{
name: 'Coupé',
matchFound: null,
},
{
name: 'Gran Coupé',
matchFound: null,
},
],
},
{
name: '3 Series',
matchFound: null,
children: [{
name: 'Sedan',
matchFound: null,
},
{
name: 'PHEV',
matchFound: null,
},
],
},
],
},
];
filteredData = [];
function filter(searchString) {
this.filteredData = this.search(this.treeData, searchString);
console.log(this.filteredData)
}
function search(children, searchString) {
return children.reduce((acc, item) => {
if (item.name.toLowerCase().includes(searchString.toLowerCase())) {
acc.push(item);
} else if (item.children && item.children.length > 0) {
const newItems = this.search(item.children, searchString);
if (newItems.length > 0) {
acc.push({
name: item.name,
children: newItems
});
}
}
return acc;
}, []);
}
this.filter('infiniti');
this.filter('luxe');
发布于 2022-10-07 08:03:43
我可以根据一些假设提出一个解决方案:
这是一个工作操场
我将粘贴代码中有意义的部分:
function filter(searchString: string) {
return treeData.map(node => search(node, searchString));
}
function search(node: CarNode, searchString: string, foundInParent = false): CarNode {
const matchFoundInNodeOrParent = foundInParent || node.name.toLowerCase().includes(searchString.toLowerCase());
const children = node?.children?.map(child => search(child, searchString ,matchFoundInNodeOrParent));
//match is found if parent or this node or at least one of th children has mathc found
const matchFound = matchFoundInNodeOrParent || ( children !== undefined && children.some(child => child.matchFound));
//return new object
return children !== undefined ? { ...node, matchFound, children } : { ...node, matchFound };
}https://stackoverflow.com/questions/73981434
复制相似问题