Kunal arora Kunal arora - 1 year ago 177
AngularJS Question

AngularJs - check if value exists in array object

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')}


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


console.log(_.has($scope.array, SelectedOptionId)); //returns false

Answer Source

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

exists = $scope.array.some(function (o) {
    return SelectedOptionId in o;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download