如果数组对象中不存在,则推送

push if not exist in array object

本文关键字:不存在 数组 对象 如果      更新时间:2023-09-26

我在JS中有以下模型。我正在使用角度 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()执行的浅层相等检查)。

如果使用 lodash 或下划线,则可以使用 _.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);
    };