2015-12-18 95 views
3

我要检查是否存在重复的output数组对象outputTypeId数组检查重复..中包含的对象作为数组

下面是JSON:

$scope.entities= [ 
     { 
      "input": { 
       "id": 134 
      }, 
      "output": [ 
       { 
        "id": 135, 
        "outputTypeId": 4 
       } 
      ] 
     }, 
     { 
      "input": { 
       "id": 134 
      }, 
      "output": [ 
       { 
        "id": 135, 
        "outputTypeId": 7 
       } 
      ] 
     }, 
     { 
      "input": { 
       "id": 134 
      }, 
      "output": [ 
       { 
        "id": 135, 
        "outputTypeId": 9 
       } 
      ] 
     } 
    ] 

下面是代码我试过但它没有在执行后的条件下..

让我[7]我检查多个outputTypeId的,因此一个数组

$scope.checkForDuplicateOutputs = (outputTypeId) => { 
     for (var i = 0; i < $scope.entities.length; i++) { 
      for (var j = i; j < $scope.entities[i].output[j].length; j++) { 

       if (outputTypeId.contains($scope.entities[i].output[j].outputTypeId)) { 
        $scope.isDuplicateOutput = true; 
        break; 
       } else { 
        $scope.isDuplicateOutput = false; 

       } 
      } 
     } 
    } 
+0

尝试grep将帮助 –

回答

1
function checkForDuplicates(outputTypeIds) { 
     $scope.isDuplicateOutput = $scope.entities.some(function(entity) { // Loop through entities 
      return entity.output.some(function(entityOutput) { // Look for any output 
       return outputTypeIds.indexOf(entityOutput.outputTypeId) != -1; // which is duplicated in 'outputTypeIds' 
      }); 
     }); 
    } 

所以这个解决方案使用Array.some - 它有几个优点:

  • ,就不再需要手动break您的循环
  • 没有必要有ij变量来跟踪循环计数器
  • 无需复制$scope.isDuplicateOutput = <boolean>;
  • 较少的代码行:)
0

您只打破了break语句的内部循环,问题在于即使重复标志设置为true,它在下一次迭代中也会重置为false。基本上,最终你只会得到最后一次迭代的结果。

最快的解决办法是使用一个标志来表示外部环路是否需要停止:

$scope.checkForDuplicateOutputs = (outputTypeId) => { 
    var breakOut = false;     // <--- this is new 
    for (var i = 0; i < $scope.entities.length; i++) { 
     if (breakOut) break;    // <--- this is new 
     for (var j = i; j < $scope.entities[i].output[j].length; j++) 
      if (outputTypeId.contains($scope.entities[i].output[j].outputTypeId)) { 
       $scope.isDuplicateOutput = true; 
       breakOut = true;   // <--- this is new 
       break; 
      } else { 
       $scope.isDuplicateOutput = false; 
      } 
     } 
    } 
} 

如果你还想要遍历所有实体,拥有所有副本的列表,你可以创建一个数组$scope.isDuplicateOutput,并且只需将重复id插入它。

相关问题