有一个需求:后端返回的菜单是通过某个字段状态为true,前端来控制显示。 这里自己造了数据:
arr: [ { a: true, child: [ { a: true, b: 2 }, { a: false, b: 3 } ] }, { a: true, child: [ { a: true, b: 2, child: [ { a: true, b: 4 }, { a: false, b: 4 } ] }, { a: true, b: 3 } ] }, { a: false, child: [ { a: false, b: 2 }, { a: false, b: 3 } ] } ]要求返回a为true的对象组成的数组
一个递归直接搞定:
const filterMenu = menuList => { return menuList.filter(item => { return item.a == true; }).map(item => { item = Object.assign({}, item) if(item.child && item.child.length > 0) { item.child = filterMenu(item.child) } return item }) } // 调用 let menuList = filterMenu(arr);结果: