javascript - 具有多个条件的过滤器数组,其中一些可以为空
问题描述
我有一个用于渲染 vuetify v-list 的 JS 文件,它可以有 2 个级别(带有子节点的节点,这些是可选的)。
我需要从用户输入的搜索框中添加一个过滤器,我可以过滤第一级,但我对第二级有问题,因为有时他们的属性“children”为空,而其他时候他们有值。菜单是这样的:
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:“
预期结果:
解决方案
您可以使用解构赋值来获取值并设置预定义值,然后使用Some您可以检查truthy
.Array
所以换句话说,你需要做的是:
filteredMenu() {
return this.menus.filter(menu => {
// check if the parent has the value
const parentIncludesText = menu.text.toLowerCase().includes(this.search.toLowerCase())
// define a predefined value in case 'children' is null
const { children = [] } = menu || {}
// check if some of the childs has the value.
const childrenIncludesText = children.some(child => child.text.toLowerCase().includes(this.search.toLowerCase()))
// then return the result of the parent and the children.
return parentIncludesText || childrenIncludesText
});
}
推荐阅读
- python - Kivy v1.11.1 嵌套框布局
- python - 有没有办法将字符串格式的字典列表转换为 Python 中的数据框?
- linux - 如何提取子目录中的所有 .tgz 文件?
- javascript - 验证 2 个元素是否具有相同的属性值
- javascript - 检查所需模块的类型以及它是否根据其类型返回正确的对象
- python - 如何获得基于时间的高标准偏差数据的置信区间?
- javascript - JavaScript 对字典数组进行排序
- android - 如何将片段目标绑定到底部导航栏中的菜单项?
- javascript - Alexa 无法连接
- php - 如何将数据从 PHP 传递到 PHP 文件