Here is the sample code,
let user =
{
fullName: "Guest User"
cart:
[
{
subTotal: 300,
product:
[
{
productName: "apple",
quantity: 3
}
]
},
{
subtTotal: 1000,
product:
[
{
productName: "orange",
quantity: 5
}
]
}
]
}
let store =
[
{
name: 'apple',
stocks: 10
},
{
name: 'orange',
stocks: 10
}
]
then I want to know the correct array methods to use to show the difference of store[index].stocks
and user.cart[index].quantity
and the result will reflect on store
I just can’t seem to know the right way to access each element in an array especially the nested ones
hope someone can help me.
Thank you in Advance! 🙂
2
Answers
Check quantity for your cart items in a forEach loop and subtract it from store value.
updateItemStocks
is a helper function to ensure that lowest value in store’s stock will be 0.You can first use
Array#flatMap
to produce an array of all the products in the user’s cart. Then,Array#reduce
can be used to create an object that maps each product to its total quantity. Finally, we useArray#map
to create a new array with decreased stocks based on the counts in the object from the previous step.