在下面的代码中,我只需要返回其中包含 meta.menu
的对象,同时保留结构。
因此,在下面的情况下,只有带有“panel.users.view”的对象才会被删除。我尝试过创建一个递归函数来遍历它,但我不知道如何无限遍历它,因为可能有更多的对象。我不知道路线对象可以达到多少层深度。
我还查看了 lodash 和 collect.js 以查看是否有可用于此目的的函数,但我无法找到解决方案我自己的。
非常感谢您的帮助,非常感谢!
const routes = [
{
path: "/panel",
name: "panel",
redirect: { name: "panel.dashboard" },
component: {},
children: [
{
path: "/dashboard",
name: "panel.dashboard",
component: {},
meta: {
menu: "main"
},
},
{
path: "/users",
name: "panel.users",
redirect: { name: "panel.dashboard" },
component: {},
children: [
{
path: "list",
name: "panel.users.list",
component: {},
meta: {
menu: "main"
},
},
{
path: "view/:user_id",
name: "panel.users.view",
component: {},
},
],
}
],
}
];
最佳答案
你可以想象一个看起来像这样的递归函数。
const res = [];
function findMeta(rs) {
rs.forEach(r => {
for (let [key, value] of Object.entries(r)) {
//console.log(`${key}`, value);
if(key === "children") findMeta(value);
if(key === "meta") res.push(r);
}
})
return res;
}
const routes = [
{
path: "/panel",
name: "panel",
redirect: { name: "panel.dashboard" },
component: {},
children: [
{
path: "/dashboard",
name: "panel.dashboard",
component: {},
meta: {
menu: "main"
},
},
{
path: "/users",
name: "panel.users",
redirect: { name: "panel.dashboard" },
component: {},
children: [
{
path: "list",
name: "panel.users.list",
component: {},
meta: {
menu: "main"
},
},
{
path: "view/:user_id",
name: "panel.users.view",
component: {},
},
],
}
],
}
];
const res = [];
function findMeta(rs) {
rs.forEach(r => {
for (let [key, value] of Object.entries(r)) {
//console.log(`${key}`, value);
if(key === "children") findMeta(value);
if(key === "meta") res.push(r);
}
})
return res;
}
console.log(findMeta(routes))
关于javascript - 深度过滤 JavaScript 数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60292441/