How to write a recursive flat map in javascript?

I have a nested route object.

Any MAY route contains a list of childRoutes routes.

I want to get a list of all routes containing the menu key.

 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'); 

The above snippet does not work recursively.

How can I do this recursively without any third-party library?

+5
source share
2 answers

how about this seems to work.

 const flatten = (routes) => { return routes.reduce((acc, r) => { if(r.childRoutes && r.childRoutes.length) { acc = acc.concat(flatten(r.childRoutes)); } else { acc.push(r); } return acc; }, []) } 

https://jsfiddle.net/vv9odcxw/

+2
source

@yBrodsky's answer can be adapted to highlight and display the general flatMap operation - here you will see that routes flattened mostly by reduce - map - concat exit the program path.

 // 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) 
+1
source

Source: https://habr.com/ru/post/1274598/


All Articles