I am trying to extract only the products in the array of objects with a product ID that exists in the masterAccessories list array which comes from a specific product that has a list of related_products in an array form.
JSON Example:
{"product":
{
"id": 3,
"product_name": "Product Name",
"sku": "sku_ID",
"description": "description",
"product_link": "link",
"cat_id": "cat-ID",
"cat_name": "Cat Name",
"related_products": [5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54]
}
},
{"product":
{
"id": 4,
"product_name": "product_name",
"sku": "sku_id",
"description": "description",
"product_link": "link",
"cat_id": "cat-tc",
"cat_name": "Cat Name",
"related_products": []
}
},
I am basically trying to find all the products with the id that exists in the related prodcuts array.
Related Products Array:
[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54]
My Attempt so far with no luck:
myPromise.then(function (result) {
let products = JSON.parse(result);
return products;
}, function (result) {
console.error(result);
}).then(function(products){
let productArray = products[0].products;
masterProduct += -1;
let accesoriesList = Object.values(productArray)[masterProduct];
let masterAccessories = accesoriesList.product.related_products;
console.log('Master: ',masterAccessories);
var newArray = [];
for(let i=0;i<productArray.length;i++){
if(masterAccessories.indexOf(productArray[i].product.id) === -1){
newArray.push(productArray[i]);
}
}
console.log('NewArray: ',newArray);
return accesoriesList;
})//just another then() that returns true
Here is one of the objects that gets returned from the productArray variable from console if it helps:
1:product:{id: 2, product_name: "Product Name", sku: "SkuID", description: "Description", product_link: "link", …} __proto__:Object
Any help would be greatly appreciated, thank you.
