AngularJS中向空数组推入唯一对象问题求解
解决向空数组推入唯一对象的循环问题
嘿,我懂你的困扰——你本来想从$scope.result里筛选出唯一对象放到空数组$scope.arr里,但原代码遍历的是空的$scope.arr,导致循环直接跳过,根本没法执行筛选逻辑对吧?
问题根源
你的原循环错误地以目标空数组作为遍历对象,而不是以有数据的$scope.result数据源为遍历主体,这就导致循环条件z < $scope.arr.length一开始就不成立(因为长度为0),循环直接终止。
正确实现思路
我们需要遍历数据源$scope.result,对每个元素检查是否已经存在于$scope.arr中,不存在就推入数组。这里以category作为判断“唯一”的标识(你可以根据需求换成其他属性或属性组合)。
代码实现方案
方案1:嵌套for循环(基础写法)
// 初始化空数组 $scope.arr = []; // 遍历数据源result for(var z = 0; z < $scope.result.length; z++) { const currentItem = $scope.result[z]; let isDuplicate = false; // 检查目标数组arr中是否已有该元素 for(var i = 0; i < $scope.arr.length; i++) { // 这里用category判断唯一性,可根据需求修改 if($scope.arr[i].category === currentItem.category) { isDuplicate = true; break; } } // 非重复则推入数组 if(!isDuplicate) { $scope.arr.push(currentItem); } }
方案2:使用Array.some()(更简洁的ES6写法)
$scope.arr = []; $scope.result.forEach(item => { // 检查arr中是否存在相同category的元素 const isDuplicate = $scope.arr.some(arrItem => arrItem.category === item.category); if(!isDuplicate) { $scope.arr.push(item); } });
自定义唯一性判断
如果你的“唯一”判断需要多个属性(比如同时比较category和categoryInt),只需要修改判断条件即可:
// 示例:多属性判断唯一性 const isDuplicate = $scope.arr.some(arrItem => arrItem.category === item.category && arrItem.categoryInt === item.categoryInt );
这样不管$scope.arr初始是否为空,都能正常从$scope.result中筛选出唯一对象并推入啦~
内容的提问来源于stack exchange,提问作者Hermes
相关产品推荐
相关产品推荐

