首页 > 解决方案 > 过滤器数组递归

问题描述

我正在寻找使用键“excludeInMenu”递归过滤我的表。我可以使用此代码过滤“项目”中的第一个表格但不能过滤第二个内容

{routes.filter(route => !route.excludeInMenu)

这是我要过滤的数组:

const routes: MenuRoute[] = [
  {
    key: 'invoice_show',
    excludeInMenu: true
  },
  {
    key: 'invoice_new'
  },
  {
    key: 'template',
    text: 'Template',
    items: [
      {
        key: 'template_contract',
        excludeInMenu: true
      },
      {
        key: 'template_invoice'
      }
    ]
  }
];

我想过滤它并得到这个结果:

     [
  {
    key: 'invoice_new'
  },
  {
    key: 'template',
    text: 'Template',
    items: [
      {
        key: 'template_invoice'
      }
    ]
  }
];

标签: javascriptreactjs

解决方案


function filterItems(items){
 return items.filter(item => !item.excludeInMenu)
}

filterItems(routes).forEach(route => {
 if(route.items){
   route.items = filterItems(route.items)
 }
});

推荐阅读