2017-09-15 100 views
3

下面是我的示例代码,通过检查项目是否已经存在,将其推入VacanciesWithSavedSearches数组。检查在推送项目之前是否存在属性值

if ($scope.VacanciesWithSavedSearches.indexOf(value) == -1) { 

      $scope.VacanciesWithSavedSearches.push({ 
       type: "Saved Searches", 
       title: value.title, 
       value: value.id 
      }); 
     } 

如何修改我上面用实际属性值替换的indexOf,如添加项目到列表VacanciesWithSavedSearches如果列表中不包含其他item.id = 123

+2

你确定你需要'VacanciesWithSavedSearches'数组?如果你正在查找唯一的ID,那么对象或地图看起来会更好。 – spanky

回答

0

使用array.filter

var result = $scope.VacanciesWithSavedSearches.filter(t=t.id ==='123'); 
if(result.length === 0) 
{ 
    $scope.VacanciesWithSavedSearches.push({ 
    type: "Saved Searches", 
    title: value.title, 
    value: value.id 
    });   

} 
1

您可以使用array.some:

如果Ecmascript6不是问题:

var id = 123; 
if (!$scope.VacanciesWithSavedSearches.some(vac => vac.id === id)) { 
    $scope.VacanciesWithSavedSearches.push({ 
     type: "Saved Searches", 
     title: value.title, 
     value: id 
    }); 
} 

随着Ecmascript5,你可以像下面:

var id = 123; 
if (!$scope.VacanciesWithSavedSearches.some(function(vac) { return vac.id === id; })) { 
    $scope.VacanciesWithSavedSearches.push({ 
     type: "Saved Searches", 
     title: value.title, 
     value: id 
    }); 
} 
+0

谢谢@cale_b,我已经更新了答案 – Faly

0

如果阵列是数字或原语的数组,你可以做.indexOf(value) == -1但它是对象的数组,所以你不能与测试.indexOf()方法,您可以使用.some()方法来测试您的对象在数组中的存在。

some()方法测试数组中是否至少有一个元素通过了由提供的函数实现的测试。

这是应该的代码:

if (!$scope.VacanciesWithSavedSearches.some(function(v){return v.value.id === -1})) { 
    $scope.VacanciesWithSavedSearches.push({ 
      type: "Saved Searches", 
      title: value.title, 
      value: value.id 
    }); 
}