JavaScript中如何通过单个函数返回两个筛选后的数组结果
问题场景
前端侧预定义枚举对象如下:
const listCodes = { makePay: 'makePay', billPay: 'billPay', yesPay: 'yesPay' }
服务端返回的响应结构、原有调用逻辑如下:
const response = [{'entitle': ['makePay', 'yesPay'], 'nonEntitle': ['billPay']}] const entitled = getList(response[0]?.entitle) const nonentitle = getList(response[0]?.nonEntitle)
原有筛选函数getList逻辑:
const getList = (list) => Object.keys(listCodes).filter((makePayList) => list?.includes(makePayList))
现有逻辑需要两次调用getList才能分别拿到已授权、未授权两个结果数组,需要优化方法实现单次调用返回两个目标结果。
优化实现
直接将接口返回的权限对象作为入参传入优化后的方法,内部仅做一次枚举遍历,同时完成两个分组的筛选,避免重复遍历开销:
const getEntitlementGroups = (permissionData) => { const entitled = [] const nonEntitled = [] // 仅遍历一次枚举键,减少重复循环 Object.keys(listCodes).forEach(codeKey => { if (permissionData?.entitle?.includes(codeKey)) { entitled.push(codeKey) } if (permissionData?.nonEntitle?.includes(codeKey)) { nonEntitled.push(codeKey) } }) return { entitled, nonEntitled } } // 单次调用即可拿到两个结果 const { entitled, nonentitle } = getEntitlementGroups(response[0])
方案优势
- 相比原两次调用的逻辑,仅做一次枚举遍历,性能更好
- 入参直接对接接口返回结构,无需提前拆分两个权限数组再传参,代码更简洁
- 保留原有可选链的边界判断逻辑,字段缺失时不会抛出运行时错误
- 后续如果新增权限分组,直接在遍历逻辑中新增判断分支即可,维护成本低
内容的提问来源于stack exchange,提问作者ganesh kaspate
相关产品推荐
相关产品推荐

