Javascript:将对象从一个数组移动到另一个数组:最佳方法? [英] Javascript: move objects from one array to another: Best approach?

查看:97
本文介绍了Javascript:将对象从一个数组移动到另一个数组:最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,分别叫做'objects'和'appliedObjects'。我试图用Javascript和/或Angular中的优雅方式将对象从一个数组移动到另一个数组。

I have two arrays, called 'objects' and 'appliedObjects'. I'm trying to come up with an elegant way in Javascript and/or Angular to move objects from one array to another.

最初我做过这样的事情:

Initially I did something like this:

   $scope.remove = function () {
        angular.forEach($scope.appliedObjects, function (element, index) {
            if (element.selected) {
                element.selected = false;
                $scope.objects.push(element);
                $scope.appliedObjects.splice(index, 1);
            }
        });
    }

   $scope.add= function () {
        angular.forEach($scope.objects, function (element, index) {
            if (element.selected) {
                element.selected = false;
                $scope.appliedObjects.push(element);
                $scope.objects.splice(index, 1);
            }
        });
    }

然后我意识到当从循环数组中删除值时,它不会添加或删除所有其他项目,因为它按索引进行。

But then I realized that when the value was removed from the looping array, and it would not add or remove every other item, since it went by index.

然后我尝试使用临时数组来保存要添加或删除的项目列表,我开始得到奇怪的参考问题。

Then I tried using a temporary array to hold the list of items to be added or removed, and I started getting strange referential issues.

我开始关注这个问题的最佳解决方案......任何帮助和/或指导非常感谢。

I'm starting to spin a bit on what the best solution to this problem would be...any help and/or guidance would much appreciated.

推荐答案

function moveElements(source, target, moveCheck) {
    for (var i = 0; i < source.length; i++) {
        var element = source[i];
        if (moveCheck(element)) {
            source.splice(i, 1);
            target.push(element);
            i--;
        }
    } 
}

function selectionMoveCheck(element) {
   if (element.selected) {
       element.selected = false;
       return true;
   }
}

$scope.remove = function () {
    moveElements($scope.appliedObjects, $scope.objects, selectionMoveCheck);
}

$scope.add = function () {
    moveElements($scope.objects, $scope.appliedObjects, selectionMoveCheck);
}

这篇关于Javascript:将对象从一个数组移动到另一个数组:最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆