[英]Check if an element exists in a object
我有一组单选按钮,当选择一个单选按钮时,该元素将推入对象。
然后,我需要获取对象中元素的值,然后将它们推入数组(如果它们尚未包含在数组中)。
我的问题是,使用此函数在每个值的数组中不断出现重复项或重复项,因为我没有正确检查它们是否存在。
如何检查元素是否已存在于我的数组中,然后将其排除在外?
_this.selected = {};
_this.selectedArray = [];
//loop through the object
angular.forEach(_this.selected, function ( item ){
//if it is not the first time the array is getting data loop through the array
if(_this.selectedArray.length > 0) {
_this.selectedArray.forEach(function (node){
//check to see if the item already exists-- this is where it is failing
//and running the loop too many times
if(node.id !== item.id){
_this.selectedArray.push(item);
}
});
} else {
_this.selectedArray.push(share);
}
});
您可以使用其他哈希值检查是否已将项目添加到数组。
_this.selected = {};
_this.selectedArray = [];
_this.selectedHash = {};
//loop through the object
angular.forEach(_this.selected, function ( item ){
if(_this.selectedHash[item.id]) { return; }
_this.selectedArray.push(item);
_this.selectedHash[item.id] = 1;
});
您是否尝试过jQuery的inArray
? http://api.jquery.com/jquery.inarray
它的工作原理与String
的indexOf
方法相同。
您可以尝试if $.inArray(node, selectedArray) == -1 // element is not in the array
您可以在该数组上运行此函数以将其减少为唯一值,而不是应用复杂的代码来检查该数组是否有元素
var getOnlyUniqueValuesInArray = function(arrayObj) {
return arrayObj.reduce(function(a, b) {
if (a.indexOf(b) < 0) a.push(b);
return p;
}, []);
};
嗨,那应该有帮助
var app = angular.module('app', []);
app.controller('firstCtrl', function($scope){
var app = angular.module('app', []);
app.controller('firstCtrl', function($scope) {
_this.selected = {};
_this.selectedArray = [];
//loop through the object
angular.forEach(_this.selected, function(item) {
//if it is not the first time the array is getting data loop through the array
if (_this.selectedArray.length > 0) {
var canAdd = true;
_this.selectedArray.forEach(function(node) {
//do not add iny any of node.id will be equal to item.id
if (node.id == item.id) {
canAdd = false;
}
});
if(canAdd){
_this.selectedArray.push(item);
};
} else {
_this.selectedArray.push(share);
}
});
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.