如何通过名称、角色、分支三个多条件过滤对象数组
实现思路
- 三个过滤条件为
且的关系,只有满足所有非空过滤条件的对象才会被保留 - 过滤参数为空时(name为空字符串、role/branch数组为空)自动跳过对应条件的校验
- 数组类型的过滤参数(role、branch)只要和目标对象的对应数组存在至少一个共同元素,即判定符合该条件
代码实现(JavaScript)
function filterUserList(userList, filterName, filterRole, filterBranch) { // 所有过滤条件为空时直接返回原列表 const isAllFilterEmpty = !filterName && filterRole.length === 0 && filterBranch.length === 0; if (isAllFilterEmpty) return userList; return userList.filter(item => { // 名称匹配,可根据需求把模糊匹配的includes改为全匹配的=== const nameMatch = !filterName ? true : item.userName.includes(filterName); // 角色匹配,可根据需求把存在交集的some改为全部包含的every const roleMatch = filterRole.length === 0 ? true : filterRole.some(role => item.roleArray.includes(role)); // 分支机构匹配,可根据需求把存在交集的some改为全部包含的every const branchMatch = filterBranch.length === 0 ? true : filterBranch.some(branch => item.branchArray.includes(branch)); return nameMatch && roleMatch && branchMatch; }) } // 测试调用 const list = [{ "userName": "name1", "roleArray": [ "role1", "role2" ], "branchArray": [ "branch1", "branch2", "branch3" ] }, { "userName": "name2", "roleArray": [ "role2", "role3" ], "branchArray": [ "branch3", "branch4", "branch5" ] }, { "userName": "name3", "roleArray": [ "role1", "role3" ], "branchArray": [ "branch1", "branch2", "branch4" ] }]; const filter_name = ""; const filter_role = ["role1","role3"]; const filter_branch = ["branch1","branch5"]; console.log(filterUserList(list, filter_name, filter_role, filter_branch))
内容的提问来源于stack exchange,提问作者Tuan Do Huu
相关产品推荐
相关产品推荐

