AngularJS如何筛选orgList中匹配tempOrgList值的对象生成新数组
实现方法
你可以直接复用已熟悉的$.grep方法完成多值匹配筛选,核心逻辑是先把待匹配的所有ItemValue提前提取出来,再过滤orgList判断是否命中匹配规则。
推荐写法(性能更优)
用Set存储待匹配值,存在性判断的时间复杂度为O(1),数据量大时性能优势明显:
// 提取tempOrgList中所有待匹配的ItemValue const targetValues = new Set($scope.tempOrgList.map(item => item.ItemValue)); // 过滤orgList,保留所有ServiceName命中匹配值的对象 $scope.resultList = $.grep($scope.orgList, function(org) { return targetValues.has(org.ServiceName); });
兼容老旧环境写法
如果运行环境不支持ES6的Set,可以用数组+indexOf实现相同效果:
const targetValues = $scope.tempOrgList.map(item => item.ItemValue); $scope.resultList = $.grep($scope.orgList, function(org) { return targetValues.indexOf(org.ServiceName) > -1; });
运行结果
基于你提供的测试数据,最终返回的结果数组会包含3条符合要求的记录:
{ServiceName: "Org1", Name: "1"}{ServiceName: "Org2", Name: "2"}{ServiceName: "Org8", Name: "8"}
内容的提问来源于stack exchange,提问作者Georgia
相关产品推荐
相关产品推荐

