Javascript:将对象从一个数组移动到另一个数组:最佳方法? [英] Javascript: move objects from one array to another: Best approach?
问题描述
我有两个数组,称为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.
最初我是这样做的:
$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屋!