angularjs 如何使用AngulsJS函数来简化for循环?

nzkunb0c  于 2022-10-31  发布在  Angular
关注(0)|答案(1)|浏览(172)

我有下面的循环,我想知道在AngularJS中是否有更有效的方法来完成这个任务。所以我想循环遍历ListA中的每一项,如果它在ListB中不存在,那么我想把项从ListA推到ListB中。但是break;停止循环,它不会遍历ListA中的所有项

for (item of $scope.ListA) {
                    let found = false;
                    for (obj of $scope.ListB) {
                        if (obj.Name == item.Name
                            && obj.Field == item.Field
                            && obj.DisplayName == item.DisplayName)
                        {
                            found = true;
                     //       console.log("double found !");
                            break;
                        }
                    }
                    if (!found)
                        $scope.ListB.push(newObj);
                }

我如何使用AngularJS函数来实现这一点?

zqry0prt

zqry0prt1#

我不知道是否有任何特定的angularjs功能,但是假设ListAListB只是javascript数组,您可以使用标准数组方法来简化您的解决方案。
例如,这里我使用array.filterarray.some...展开运算符:

// Scope example
const $scope = {
  ListA: [
    { Name: 'name1', Field: 'field1', DisplayName: 'displayName1' },
    { Name: 'name2', Field: 'field2', DisplayName: 'displayName2' },
    { Name: 'name3', Field: 'field3', DisplayName: 'displayName3' },
  ],
  ListB: [
    { Name: 'name2', Field: 'field2', DisplayName: 'displayName2' },
    { Name: 'name4', Field: 'field4', DisplayName: 'displayName4' },
  ],
};

// A function that checks if a list contains an item
const hasItemInList = (item, list) => {
  // Here we use "array.some" method, which returns "true" if condition is true for any of the array items
  return list.some(listItem => 
    listItem.Name == item.Name &&
    listItem.Field == item.Field &&
    listItem.DisplayName == item.DisplayName
  );
}

// Getting the array of items that should be added to the listB,
// Here we use "array.filter" to filter the items of array by provided condition
const itemsToAdd = $scope.ListA.filter(item => !hasItemInList(item, $scope.ListB));

// And here we push all the items to the listB,
// we use a spread operator "..." here to push all the items of array at once
$scope.ListB.push(...itemsToAdd);

console.log($scope.ListB);

数组方法-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

相关问题