I built a courses page with 3 courses, i want to build it in a way that all the courses are displayed with a buy button, the course info is collected from the database via the products
collection. then i want that if the user bought the course, instead of buy, watch will be displayed.
to do that i have 2 arrays: 1) all the products 2) the products that the user bought
now i want to compare them, and delete from the first array all the products that the user already bought.
i tried checking online for methods, but i didn't understand them at all.
Here is the function to get the arrays:
const productRef = await db.collection("products").get();
const products = await productRef.docs.map(doc => {
return {
id: doc.id,
name: doc.data().name,
price: doc.data().price
};
});
console.log(products);
//[ { id: 'course1', name: 'Course 1', price: 25 },
{ id: 'course2', name: 'Course 2', price: 10 },
{ id: 'course3', name: 'Course 3', price: 30 } ]
if (user) {
const claims = res.locals.decodedClaims;
const uid = claims.uid;
const email = claims.email;
const userProductsRef = await db
.collection("users")
.doc(uid)
.collection("courses")
.get();
if (userProductsRef.docs.length > 0) {
const userProducts = userProductsRef.docs.map(doc => {
return { id: doc.id, name: doc.data().name };
});
console.log(userProducts);//[ { id: 'course1', name: 'Course 1' } ]
///COMPARE HERE the two arrays
}
}
now i want to compare products with userProducts by the id.
so expected result at the end should be something like:
products= [
{ id: 'course2', name: 'Course 2', price: 10 },
{ id: 'course3', name: 'Course 3', price: 30 } ];
userProducts= [ { id: 'course1', name: 'Course 1' } ]
Thank You!
You can filter the products
array by checking to see if each product id is in the userProducts
array:
const filteredProducts = products
.filter(prod => !userProducts.find(userProd => userProd.id === prod.id))
console.log(filteredProducts)
// [
// { id: 'course2', name: 'Course 2', price: 10 },
// { id: 'course3', name: 'Course 3', price: 30 }
// ]
I hope this is what you were looking for.
You could use a combination of .filter()
and .find()
to achieve what you want:
const products = [ { id: 'course1', name: 'Course 1', price: 25 }, { id: 'course2', name: 'Course 2', price: 10 }, { id: 'course3', name: 'Course 3', price: 30 }, ]; const userProducts = [ { id: 'course1', name: 'Course 1' } ]; const result = products.filter(product => { return !userProducts.find(o => o.id === product.id); }); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.