简体   繁体   中英

check if property value exist before push item

Below is my sample code that pushes into VacanciesWithSavedSearches array by checking if the item does not already exist.

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

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

How do I change the above by replacing indexOf with the actually property value, eg Add item to the list VacanciesWithSavedSearches if the list do not contain another item.id=123

use 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
   });          

}

You can use array.some:

If Ecmascript6 is not a problem:

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

With Ecmascript5, you can do it like below:

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

If your array was an array of numbers or primitives you could do .indexOf(value) == -1 but it's an array of objects so you can't test it with .indexOf() method, you can use .some() method to test over the existence of your object in the array.

The some() method tests whether at-least one element in the array passes the test implemented by the provided function.

This is how should be your code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM