I have an array of products and an array of products that a user has access to. They share a common ID. I want to filter the array of products to only return those that the user has access to.
All products (products
)
[{
"productName": "My Product"
"p_id": "1"
},...
]
My available products (myProducts
)
[
{
"i_items": "[{\"act\":\"new\",\"app\":\"nexus\",\"type\":\"package\",\"cost\":\"0.00\",\"tax\":null,\"quantity\":1,\"itemName\":\"My Product\",\"itemID\":1,\"physical\":false,\"methods\":\"*\",\"cfields\":[],\"extra\":null,\"renew_term\":1,\"renew_units\":\"m\",\"renew_cost\":\"100.00\",\"grace_period\":86400}]"
},...
]
Edit:
The below solution is returning []
// Extract available IDs into a Set:
const availableIds = new Set(this.myProducts.flatMap(({i_items}) =>
JSON.parse(i_items).map(item => ""+item.itemID))
);
console.log(availableIds); //Set(1) {"3"}
// Use the Set to filter the products:
console.log(availableIds.has("3")); //true
const filtered = this.products.filter(({p_id}) => availableIds.has(p_id));
console.log(filtered); // []
Final edit: thanks to everyone who helped. This last issue was caused by not casting the id to string. Once I changed availableIds.has(p_id)
-> availableIds.has(""+p_id)
it worked.