Typescript-获取满足条件的数组

时间:2018-12-12 10:30:38

标签: javascript angular typescript ecmascript-6 angular6

是否可以从给定的包含role = 1的给定输出数组中没有重复项? Iam使用角度6打字稿。是否有任何打字稿数组处理功能可以执行此操作   //输入数组

export const userMenus = [
{
    name: 'Dashboard',
    url: '/dashboards',
    icon: 'icon-speedometer',
    roles:'1,3,4'
},
  {
    name: 'Users',
    url: '/Users',
    icon: 'icon-bell',
    roles:'1,2,3,4'
  },
  {
    name: 'Article',
    url: '/Users',
    icon: 'icon-bell',
    roles:'1,2,3,4',
    children: [
             {
              name: 'Cards',
               url: '/base/cards',
               icon: 'icon-puzzle',
               roles:'1,3,4',
             },
             {
               name: 'Carousels',
               url: '/base/carousels',
               icon: 'icon-puzzle',
               roles:'2,4',
             },
             {
               name: 'Collapses',
               url: '/base/collapses',
               icon: 'icon-puzzle',
               roles:'4'
             }
            ]      
  }

]

-如果角色为2,则需要输出。 删除了角色字段中不包含2的项目

userMenus = [
  {
    name: 'Users',
    url: '/Users',
    icon: 'icon-bell',
    roles:'1,2,3,4'
  },
  {
    name: 'Article',
    url: '/Users',
    icon: 'icon-bell',
    roles:'1,2,3,4',
    children: [
             {
               name: 'Carousels',
               url: '/base/carousels',
               icon: 'icon-puzzle',
               roles:'2,4',
             },
            ]      
  }

1 个答案:

答案 0 :(得分:1)

您必须过滤阵列并确认您的角色中有2位:

const filteredUserMenus = userMenus.filter((userMenu) => {
  return userMenu.roles.find((role) => role === '2');
});

简短语法:

const filteredUserMenus = userMenus.filter((userMenu) => 
  userMenu.roles.find((role) => role === '2'));

编辑:您的数据结构不正确,角色不应该是字符串而是角色数组。无论如何,如果您不能更改它,这是一个解决方案:

const filteredUserMenus = userMenus.filter((userMenu) => {
  return userMenu.roles.split(',').find((role) => role === '2');
});

简短语法:

const filteredUserMenus = userMenus.filter((userMenu) =>
   userMenu.roles.split(',').find((role) => role === '2'));