簡體   English   中英

如果數組對象中不存在,則推送

[英]push if not exist in array object

我在JS中有以下模型。 我正在使用angular js

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

我有以下功能:

$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);

        };

我想推送過濾器(如果尚不可用)。 我怎樣才能做到這一點。

我已經在上面嘗試過,但是工作很辛苦。 什么地方出了錯。 誰能幫幫我嗎,

謝謝,

因此,我假設$scope.data.Filters是具有FilterNameFilterValue屬性的對象數組。

在這種情況下,實際上,您需要通過比較對象的屬性值來搜索數組以查看是否存在匹配的對象,方法是比較該對象的屬性值(深層相等檢查,而不是淺層相等檢查,即indexOf()一樣)。

如果使用lodashunderscore ,則可以使用_.findWhere()幫助器輕松完成此操作:

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

否則,您可以創建自己的函數,因此完整的代碼如下所示:

$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;
}

試試看:

$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);

    };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM