AngularJS在第一个数组中查找对象,该对象未在第二个数组中呈现

AngularJS find object in first array which is not presented in second

本文关键字:数组 对象 第二个 查找 AngularJS 第一个      更新时间:2023-09-26

假设我有两个对象:

第一:

[
    {
        id: "123",
        title: "123",
        options: []
    },
    {
        id: "456",
        title: "456",
        options: [
            {
                id: "0123",
                title: "0123",
                options: []
            }
        ]
    },
    {
        id: "789",
        title: "789",
        options: []
    },
]

第二个

[
    {
        id: "123",
        title: "123",
        options: []
    },
    {
        id: "789",
        title: "789",
        options: []
    },
]

正如您在第二个数组中看到的那样,我缺少这部分:

{ 编号: "456", 标题: "456", 选项:[ { 编号: "0123", 标题:"0123", 选项: [] } ]}

在 Angular 中迭代和查找缺失的元素如何正确和更好?

你可以这样做

<div ng-app>
    <div ng-controller="MyCtrl">{{availableGroups}}
    </div>
</div>

JS代码

function MyCtrl ($scope) {
    $scope.groups = [
    {
        id: "123",
        title: "123",
        options: []
    },
    {
        id: "456",
        title: "456",
        options: [
            {
                id: "0123",
                title: "0123",
                options: []
            }
        ]
    },
    {
        id: "789",
        title: "789",
        options: []
    },
];
    $scope.assignedGroups = [
    {
        id: "123",
        title: "123",
        options: []
    },
    {
        id: "789",
        title: "789",
        options: []
    },
];

    $scope.availableGroups = (function () {
        var assignedGroupsIds = {};
        var groupsIds = {};
        var result = [];
        $scope.assignedGroups.forEach(function (el, i) {
          assignedGroupsIds[el.id] = $scope.assignedGroups[i];
        });
        $scope.groups.forEach(function (el, i) {
          groupsIds[el.id] = $scope.groups[i];
        });
        for (var i in groupsIds) {
            if (!assignedGroupsIds.hasOwnProperty(i)) {
                result.push(groupsIds[i]);
            }
        }
        return result;    
    }());
}

这是工作 jsFiddle

谢谢

假设第一个数组名为 first,第二个数组名为 second 。现在先对它们进行排序:

function comp(a, b){
    if(a.id < b.id) return -1;
    if(a.id > b.id) return 1;
    return 0;
}
first.sort(comp);
second.sort(comp);

然后遍历它们以查找缺少的元素:

var missing = {};
for(var i = 0, j = 0; i < first.length; ++i){
    if(first[i].id == second[j].id){
        j++;
        continue;
    }
    missing.push(first[i]);
}

missing数组现在包含第一个数组中的对象,但不包含第二个数组中的对象。

请注意,我没有使用AngularJS;它是普通的Javascript。