AngularJs - check if value exists in array object

15,050

You could use Array#some and check with in operator.

exists = $scope.array.some(function (o) {
    return SelectedOptionId in o;
});
Share:
15,050
Kunal arora
Author by

Kunal arora

Updated on June 04, 2022

Comments

  • Kunal arora
    Kunal arora almost 2 years
    var SelectedOptionId = 957;
    
    $scope.array = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}]
    

    Is there a way of checking if a value exists in an that kind of array objects. I am using Angular and underscore.

    I have tried all this -

    if ($scope.array.indexOf(SelectedOptionId) === -1) {console.log('already exists')}
    

    and

    console.log($scope.array.hasOwnProperty(SelectedOptionId)); //returns false
    

    and

    console.log(_.has($scope.array, SelectedOptionId)); //returns false 
    
  • Rajesh
    Rajesh over 7 years
    I have learned more just by reading your answers than googling. Thanks for being awesome. :-)
  • Kunal arora
    Kunal arora over 7 years
    How to do it for the values i.e.- instead of 957 I want to do it for 1269
  • Nina Scholz
    Nina Scholz over 7 years
    for values, you need to iterate over the keys of the object, and check against, like return Object.keys(o).some(function (k) { return o[k] === value; });