backtrack
backtrack

Reputation: 8154

push if not exist in array object

I have the below model in JS . I am using angular js

$scope.data = {
            FocusOn: " ",
            Filters: [],
            Range: {
                From: "",
                To: ""
            }
        }

I have the below function :

$scope. addField = function ($type, $value) {
            $scope.data1 = {
                FilterName: $type,
                FilterValue: $value
            };
            if ($scope.data.Filters[$type] === undefined) {
                $scope.data.Filters.push($scope.data1);
            }
            $scope.data1 = "";
            $scope.Json = angular.toJson($scope.data);

        };

I want to push the Filters if it is not available already. How can i do this.

I have tried above but dint work. What went wrong. Can anyone please help me,

Thanks,

Upvotes: 1

Views: 5405

Answers (2)

GregL
GregL

Reputation: 38161

So I am assuming that $scope.data.Filters is an array of objects with a FilterName and FilterValue property.

In that case, you actually need to search the array to see if a matching object exists before inserting it, by comparing the values of the properties of the object (a deep equality check, as opposed to a shallow equality check, which indexOf() does).

If you use lodash or underscore, you can use the _.findWhere() helper to do this easily:

if (!_.findWhere($scope.data.Filters, $scope.data1)) {
    $scope.data.Filters.push($scope.data1);
}

Otherwise, you could make your own function, so your full code looks like:

$scope.addField = function ($type, $value) {
    $scope.data1 = {
        FilterName: $type,
        FilterValue: $value
    };
    if (!filterExists($type)) {
        $scope.data.Filters.push($scope.data1);
    }
    $scope.data1 = "";
    $scope.Json = angular.toJson($scope.data);
};

function filterExists(type) {
    for (var i = 0, len = $scope.data.Filters.length; i < len; i++) {
        if ($scope.data.Filters[i].FilterName === type)
            return true;
    }
    return false;
}

Upvotes: 2

Efog
Efog

Reputation: 1179

Try that:

$scope.addField = function ($type, $value) {
        $scope.data1 = {
            FilterName: $type,
            FilterValue: $value
        };
        if ($scope.data.Filters[$type] == undefined) {
            $scope.data.Filters[$type] = $scope.data1;
        }
        $scope.data1 = "";
        $scope.Json = angular.toJson($scope.data);

    };

Upvotes: 0

Related Questions