我有一个 JS 文件,用于渲染 vuetify v-list,它可以有 2 个级别(带有子节点的节点,这些是可选的)。
我需要从用户输入的搜索框中添加一个过滤器,我可以过滤第一个级别,但我在第二个级别上遇到问题,因为有时它们的属性“children”为 null,而其他时候它们有值。菜单是这样的:
const Menu = [
{
heading: null,
icon: "mdi-security",
text: "Login",
url: {
name: "login"
},
exactUrl: false,
children: null,
meta: {
publicPath: true
}
},
{
heading: null,
icon: "search",
text: "Lista de Funcionarios",
url: {
name: "home"
},
exactUrl: true,
children: null,
meta: {
publicPath: true
}
},
{
heading: {
text: "Mantenimientos",
publicPath: false
},
icon: null,
text: "",
url: null,
exactUrl: null,
children: null,
meta: null
},
{
heading: null,
icon: "mdi-account-group",
text: "Departamentos",
url: {
name: "departamentos"
},
exactUrl: false,
children: null,
meta: {
publicPath: false
}
},
{
heading: null,
icon: "mdi-account-circle",
text: "Funcionarios",
url: {
name: "funcionarios"
},
exactUrl: false,
children: null,
meta: {
publicPath: false
}
},
{
heading: null,
icon: "settings",
text: "Operación",
url: null,
exactUrl: false,
children: [{
icon: "add",
text: "Cargar Pedidos",
url: {
name: "departamentos"
}
},
{
icon: "playlist_add_check",
text: "Aprobar Pedidos",
url: {
name: "areas"
}
},
{
icon: "content_copy",
text: "Remitir Pedidos",
url: {
name: "maps"
}
}
],
meta: null
},
];
export default Menu;
我的计算函数是这样的:
filteredMenu() {
return this.menus.filter(menu =>
menu.text.toLowerCase().includes(this.search.toLowerCase())
);
}
如何同时在两个级别上进行过滤?
编辑1:“
预期结果:
最佳答案
我认为您正在寻找类似的东西,它当然使用递归。不过,它使用递归的方式很重要,这意味着您要首先探测子级,然后确定是否存在子级(保留父级),或当前是否存在菜单项具有给定的文本,它匹配。您将需要任何匹配的子项的父项,对于菜单结构的每个分支一直向内,然后返回到根级项。
这将调用子项上的探测器,然后进一步向内运行整个过程,直到没有子项为止,返回每个带有匹配项的内部集(及其关联的父项),然后备份以处理下一个更高的项等级。像这张图一样思考,
1 match
2 match
3az < match
3ay < match
3ax < match
3a < [...match] match
3b < match
3 [...match] match
4a < match
4 [...match] match
5 match
此外,您不想过滤,您想减少到一个集合。
const search = (items, text) => {
const hasText = item => item.text.toLowerCase().includes(text.toLowerCase())
const probe = (found, item) => {
item.children = (item.children || []).reduce(probe, [])
if (item.children.length || hasText(item)) {
found.push(item)
}
return found
}
return items.reduce(probe, [])
}
... elsewhere ...
return search(this.menus, 'c')
https://jsfiddle.net/81wkh5df/6/
这将返回:
- 函数列表
- 仿函数
- 操作
- 卡加佩多斯
关于javascript - 具有多个条件的过滤数组,其中一些可以为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59898972/