我有以下JavaScript,其中包含两个对象和 id 和一个属性。
如何检查B中是否包含A中的特定组合(id + attr tupel)?那么currentHMLMap[i]
是否包含在整个newHTMLMap
对象的任何地方?
deleteLinks.on('click', function(ev){
ev.preventDefault();
var currentHTML = $('.product');
var currentId = $("body").find('.product').toArray().map(function(e){return $(e).attr("data-id-product");});
var currentAtr = $("body").find('.product').toArray().map(function(e){return $(e).attr("data-id-product-attribute");});
currentHTMLMap = currentId.map(function(x, i) {
return{"id": x, "atr" : currentAtr[i]}
}.bind(this));
var newHTML ;
var deleteIndices = [];
$.ajax({
url: this.href,
type: "GET",
dataType: "html",
success: function(data) {
newHTMLId = $(data).find('.product').toArray().map(function(e){ return $(e).attr("data-id-product");})
newHTMLAtr = $(data).find('.product').toArray().map(function(e){ return $(e).attr("data-id-product-attribute");})
//creating "map"
newHTMLMap = newHTMLId.map(function(x, i) {
return{"id": x, "atr" : newHTMLAtr[i]}
}.bind(this));
for(i = 0; i < currentHTML.length; i++){
// is currentHMLMap[i] included in newHTMLMap?
if (??){
deleteIndices.push(i);
}
}
for(i = 0; i < deleteIndices.length; i++) {
console.log("removing index" + deleteIndices[i]);
currentHTML[deleteIndices[i]].remove();
}
}
});
});
更新:
currentHTMLMap:
0: {id: 1, atr: 5}
1: {id: 3, atr: 71}
newHTMLMap:
0: {id: 3, atr: 71}
newHTMLMap可能包含多个条目,并且可能删除了多个元素。
因此newHTMLMap中不包含currentHTMLMap的第一个索引,因此我想将0推送到deleteIndices
。
我希望这有助于澄清。
答案 0 :(得分:0)
var a = [
{id: 1, atr: 5},
{id: 3, atr: 71}
]
var b = {id:1, atr: 7}
var found = false;
a.forEach(function(el){
if(JSON.stringify(el) === JSON.stringify(b)){
found = true;
}
});
console.log(found);
var a = [
{id: 1, atr: 5},
{id: 3, atr: 71},
{id: 4, atr: 81},
{id: 5, atr: 91},
{id: 6, atr: 171}
]
var b = [
{id:1, atr: 7},
{id:1, atr: 5},
{id: 5, atr: 91}
]
var found = false;
var matches = [];
a.forEach(function(aEl,aElIndex){
b.forEach(function(bEl, bElIndex){
if(JSON.stringify(aEl) === JSON.stringify(bEl)){
matches.push({
"aElIndex": aElIndex,
"bElIndex": bElIndex
})
}
})
});
console.log(matches);
答案 1 :(得分:0)
使用类似此功能的对象containsObject()
var data = [
{id: 1, atr: 5},
{id: 3, atr: 71}
];
var data2 =[
{id: 3, atr: 71}
];
function containsObject(obj, list) {
var i;
var x;
for(x=0;x<obj.length;x++)
for (i = 0; i < list.length; i++) {
if (list[i] === obj[x]) {
return true;
}
}
}
return false;
}
containsObject(data2,data);