如何在添加对象之前检查对象是否已经存在?
问题描述:
我有这个algorithme问题,我想检查对象是已经出现在我的数组将它添加之前。如何在添加对象之前检查对象是否已经存在?
我尝试了许多不同的方法(的indexOf,过滤器......),我的最后一次尝试是有angular.foreach。
问题是我的$ scope.newJoin仍然总是空的。我恍然大悟,那是因为0大小我的$ scope.newJoin的,因为如果没有念过,但我不知道怎么算出这个...
$ scope.newJoinTMP由组成:6点的对象,每一个内timePosted属性(用于比较这些不同阵列对象)。
$ scope.newJoin是一个空数组。我想用它填充里面的Objects $ scope.newJoinTMP但是肯定有一次每个对象,并不是两倍相同($ scope.newJoinTMP可以有重复的对象里面,但是$ scope.newJoin mustn' T)。
angular.forEach($scope.newJoinTMP, function(item)
{
angular.forEach($scope.newJoin, function(item2)
{
if (item.timePosted === item2.timePosted)
{
//snap.val().splice(snap.val().pop(item));
console.log("pop");
}
else
{
$scope.newJoin.push(item);
console.log("newJoin :", $scope.newJoin);
}
});
});
答
您可以使用reduce
$scope.newJoin = $scope.newJoinTMP.reduce(function(c, o, i) {
var contains = c.some(function(obj) {
return obj.timePosted == o.timePosted;
});
if (!contains) {
c.push(o);
}
return c;
}, []);
的问题与当前的代码,如果newJoin
是空的,什么都不会被添加到它 - 如果它不是空,如果第一次迭代与newJoinTMP
中正在迭代的当前项目不匹配 - 您正在推送。
答
if(!$scope.newJoin.find(el=>item.timePosted===el.timePosted){
$scope.newJoin.push(item);
console.log("newJoin :", $scope.newJoin);
}
你不想推送的forEach内,因为这会推多次...
答
可能有更好的方式来处理你的特殊情况,但这里是为您的特定代码修复。 替换你内心的每一个与一些这对于元素的存在,并通过布尔值返回布尔值,决定是否加元或不
angular.forEach($scope.newJoinTMP, function(item)
{
var isItemPresent = $scope.newJoin.some(function(item2)
{
return item.timePosted === item2.timePosted;
//you dont need this conditional handling for each iteration.
/* if (item.timePosted === item2.timePosted)
{
//snap.val().splice(snap.val().pop(item));
console.log("pop");
}
else
{
$scope.newJoin.push(item);
console.log("newJoin :", $scope.newJoin);
} */
});
if(! isItemPresent) {
$scope.newJoin.push(item);
} else {
//do if it was present.
}
});
答
如果你想避免嵌套循环(的forEach,一些的indexOf ,或者其他),你可以使用一个辅助对象。它会使用更多的记忆,但你会花更少的时间。
let arr = [{ id: 0 }, { id:0 }, { id: 1}];
let aux = {};
const result = arr.reduce((result, el) => {
if (aux[el.id] === undefined) {
aux[el.id] = null;
return [el, ...result];
} else {
return result;
}
}, []);
console.log(result);
哦这是一个错误,我一直在做的,谢谢你指出它...如何更换一个foreach里推? 在每个循环中增加一个简单的索引值?像这样:$ scope.newJoin [i] = item? – Memphis
@memphis:再看看我的代码(它已经包含了答案;)) –