I have a generic object ( availableProducts
), whose properties are arrays of objects of different types ( type1
, type2
, ...).
On the other hand I have a specific array of objects ( specificProducts
).
I need that if an object of whatever type (contained in type1
, type2
, ...) does NOT exist with that ID
in the specific array ( specificProducts
), it is removed from availableProducts
.
I have managed to do the opposite, that if it exists, I delete it, but the other way around, the verification is different, I have blocked myself and I do not know very well how to do that verification.
I put my code:
var availableProducts = {type1:[],type2:[],type3:[]};
product1 = {id:"8sdgs7dfgg7e", name:"A1", description:"desc1"};
product2 = {id:"h78sghfg7asd", name:"A2", description:"desc2"};
product3 = {id:"hay78d7887ss", name:"A3", description:"desc3"};
product4 = {id:"fa67dgshgfsc", name:"A4", description:"desc4"};
availableProducts.type1.push(product1);
availableProducts.type2.push(product2);
availableProducts.type2.push(product3);
availableProducts.type3.push(product4);
console.log("availableProducts antes", availableProducts);
var specificProducts = [];
productData1 = {ref:"001", id:"hay78d7887ss", brand:"brand1"};
productData2 = {ref:"002", id:"h78sghfg7asd", brand:"brand2"};
specificProducts.push(productData1);
specificProducts.push(productData2);
console.log("specificProducts antes", specificProducts);
for (var product in availableProducts){
for (var i=0; i < availableProducts[product].length; i++) {
for (var j=0; j < specificProducts.length; j++) {
if (availableProducts[product][i] != undefined) {
if (availableProducts[product][i].id == specificProducts[j].id) {
console.log(availableProducts[product][i].id + " is the same as "+ specificProducts[j].id);
} else {
console.log(availableProducts[product][i].id + " is different as "+ specificProducts[j].id);
availableProducts[product].splice(i,1);
//delete availableProducts[product][i];
//elimina todo y deja vacíos los arrays, cómo hago esto de otra forma??
}
}
}
}
}
console.log("availableProducts después", availableProducts);
In the end, if they are different, it empties all the data as you can see, I imagine it is because in the for loop it checks one by one. I don't know how to fix this, thanks.