gpt4 book ai didi

javascript - 递归过滤 bool 键的数据

转载 作者:行者123 更新时间:2023-12-01 00:45:21 26 4
gpt4 key购买 nike

我的导航从 vue-router 获取路线,这样我就不必手动添加它们。

这些路由及其子路由都有一个名为“inMenu”的元 bool 键。我只过滤了父路由,但没有过滤子路由。

var res = this.$router.options.routes.filter(function f(o) {
if (o.route.meta.inMenu === true) return true

if (o.children) {
return (o.children = o.children.filter(f)).length
}
})

这就是我过滤父路由的方式,但我无法管理它来过滤子路由。

return this.$router.options.routes.filter(route => route.meta.inMenu === true);

这是一些示例数据:

{
"path": "/orders",
"component": {
"name": "Orders",
"__file": "src/views/Orders.vue",
},
"meta": {
"icon": "fa-history",
"title": "Abwicklungen",
"inMenu": true
},
"children": [
{
"path": "list",
"name": "orderList",
"component": {
"name": "OrderList",
"__file": "src/views/orders/list.vue",
},
"meta": {
"title": "Bestellliste",
"icon": "fa-circle-o",
"inMenu": true
}
},
{
"path": "details/:id",
"name": "orderDetails",
"component": {
"name": "OrderDetails",
"__file": "src/views/orders/details.vue"
},
"meta": {
"title": "Bestellung",
"icon": "fa-circle-o",
"inMenu": false
}
},
{
"path": "dailyclosing",
"component": {
"name": "OrderList",
"__file": "src/views/orders/list.vue",
},
"meta": {
"title": "Tagesabschluss",
"icon": "fa-check",
"inMenu": true
}
}
]
}

如果 inMenu 为 false,我希望不显示每条路线和子路线。

最佳答案

假设您希望所有对象都具有真正的 inMenu 属性,您可以使用新的子对象构建一个新数组。没有 true inMenu 项目的分支将被过滤掉。

function filter(array) {
return array.reduce((r, { children = [], ...o }) => {
children = filter(children);
if (o.meta.inMenu || children.length) r.push(Object.assign({}, o, children.length && { children }));
return r;
}, [])
}

var data = [{ path: "/orders", meta: { icon: "fa-history", title: "Abwicklungen", inMenu: true }, children: [{ path: "list", name: "orderList", meta: { title: "Bestellliste", icon: "fa-circle-o", inMenu: true } }, { path: "details/:id", name: "orderDetails", meta: { title: "Bestellung", icon: "fa-circle-o", inMenu: false } }, { path: "dailyclosing", meta: { title: "Tagesabschluss", icon: "fa-check", inMenu: true } }] }, { path: "/orders", meta: { icon: "fa-history", title: "Abwicklungen", inMenu: false }, children: [{ path: "list", name: "orderList", meta: { title: "Bestellliste", icon: "fa-circle-o", inMenu: true } }, { path: "details/:id", name: "orderDetails", meta: { title: "Bestellung", icon: "fa-circle-o", inMenu: false } }, { path: "dailyclosing", meta: { title: "Tagesabschluss", icon: "fa-check", inMenu: true } }] }],
result = filter(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 递归过滤 bool 键的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57426355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com