gpt4 book ai didi

javascript - 如何在 javascript 中编写递归平面 map ?

转载 作者:数据小太阳 更新时间:2023-10-29 05:17:32 25 4
gpt4 key购买 nike

我有一个嵌套路由的对象。

任何路线可以包含路线列表childRoutes

我想获取包含键 menu 的所有路由的列表。

const routes = [{
"name": "userManagement",
"childRoutes": [
{
"name": "blogManagement",
"childRoutes": [
{
"name": "blog", // <=== I want to have this route
"menu": {
"role": 1020
}
}
],
},
{
"name": "organizationList", // <=== and this one
"menu": {
"role": 1004
}
}

],
}, {
"name": "test",
"menu": { "role": 4667 }
}];

const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));

// Should handle nesting of route
const links = deepFlatten(routes).filter((r) => !!r.menu);

console.log('it should have a length of 3:', links.length === 3);
console.log('it should be blog:', links[0].name === 'blog');
console.log('it should be organizationList:', links[1].name === 'organizationList');
console.log('it should be test:', links[2].name === 'test');

上面的代码片段还不能递归地工作。

在没有任何第三方库的情况下,我如何递归执行此操作?

最佳答案

@yBrodsky 的回答可以用来隔离和展示通用的 flatMap 操作——在这里,你会看到路线被扁平化了很多 reduce-map-concat 为程序员开路。

// polyfill if you don't have it
Array.prototype.flatMap = function (f)
{
return this.reduce ((acc, x) =>
acc.concat (f (x)), [])
}

// your data
const routes =
[ { name : "userManagement"
, childRoutes :
[ { name : "blogManagement"
, childRoutes :
[ { name : "blog"
, menu : { role : 1020 }
}
]
}
, { name : "organizationList"
, menu : { role : 1004 }
}
]
}
, { name : "test"
, menu : { role : 4667 }
}
]

// flat-mapped routes
const allChildRoutes =
routes.flatMap (function loop (node) {
if (node.childRoutes)
return node.childRoutes.flatMap (loop)
else
return [node]
})

console.log (allChildRoutes)

关于javascript - 如何在 javascript 中编写递归平面 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48171842/

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