在 javascript 上使用平面图,有条件

use flatmap on javascript, with condition

我正在创建一个处理监视和编辑权限的组件。 我用来保存权限的数据结构如下所示:

const input = [{
    isAllowed: true,
    permissionType: "watch",
    userId: 14
  },
  {
    isAllowed: false,
    permissionType: "edit",
    userId: 14
  },
  {
    isAllowed: true,
    permissionType: "edit",
    userId: 24
  },
  {
    isAllowed: false,
    permissionType: "edit",
    userId: 34
  },
  {
    isAllowed: false,
    permissionType: "watch",
    userId: 44
  },
  {
    isAllowed: false,
    permissionType: "edit",
    userId: 44
  }
]

起初,我只是想获得所有具有任何权限的用户的列表,所以我会使用

let managers = _.flatMap(props.settings.managerPermissions, (p) => p.userId);
managers = [...new Set(managers)];

所以这会给我留下 managers = [14,24,34,44],但我需要以一种我不会取回根本没有权限的管理员 ID 的方式编辑此平面图,即使添加了它们也是如此已经添加到列表中,所以在这种情况下,新平面图的 return 值应该是 managers = [14,24]。 (当然 flatMap 在这里不是必须的,如果有更好的方法我会很高兴看到它)

当 map 的结果是一个数组数组,而你想要一个平面数组时,你只需要 flatMap。

在这种情况下,按 isAllowed 过滤数组,然后映射到 userId:

const arr = [{"isAllowed":true,"permissionType":"watch","userId":14},{"isAllowed":false,"permissionType":"edit","userId":14},{"isAllowed":true,"permissionType":"edit","userId":24},{"isAllowed":false,"permissionType":"edit","userId":34},{"isAllowed":false,"permissionType":"watch","userId":44},{"isAllowed":false,"permissionType":"edit","userId":44}]

const managers = [...new Set(
  arr
  .filter(o => o.isAllowed)
  .map(o => o.userId)
)]

console.log(managers)

然而,您实际上使用 Array.flatMap()(或 lodash 等价物)同时进行映射和过滤。 map/filter 组合不太惯用,而且我不确定性能,所以我自己不使用它。这个想法是 return 一个空数组来存放你不想要的项目:

const arr = [{"isAllowed":true,"permissionType":"watch","userId":14},{"isAllowed":false,"permissionType":"edit","userId":14},{"isAllowed":true,"permissionType":"edit","userId":24},{"isAllowed":false,"permissionType":"edit","userId":34},{"isAllowed":false,"permissionType":"watch","userId":44},{"isAllowed":false,"permissionType":"edit","userId":44}]

const managers = [...new Set(
  arr.flatMap(o => o.isAllowed ? o.userId : [])
)]

console.log(managers)

你应该能够过滤掉 isAllowed=false 然后做同样的事情 - 虽然 flatMap 似乎没有用(因为没有数组嵌套) - 只需使用 map

const input = [
 {isAllowed: true,
  permissionType: "watch",
  userId : 14
 },
 {isAllowed: false,
  permissionType: "edit",
  userId : 14
 },
 {isAllowed: true,
  permissionType: "edit",
  userId : 24
 },
 {isAllowed: false,
  permissionType: "edit",
  userId : 34
 },
 {isAllowed: false,
  permissionType: "watch",
  userId : 44
 },
 {isAllowed: false,
  permissionType: "edit",
  userId : 44
 }]
 
 const managers = [...new Set(input.filter(x => x.isAllowed).map(x => x.userId))];
 console.log(managers);