'Loop through objects and subtract different objects values
As you might see the data structure looks like:
Dining Chair with the corresponding parts (productList state):
0: {id: '0517f083-0e15-4876-8d1f-6fa45900431c', amountRequired: 4}
1: {id: '831b92b8-677b-42cc-a585-335ea4ccccb6', amountRequired: 1}
2: {id: 'addc65a8-c759-41d8-a18a-89fe446ad484', amountRequired: 8}
length: 3
id: "a269a247-0d38-4b47-9630-79c9ae545b68"
name: "Dining Chair"
Stock (articleList state)
{id: '0517f083-0e15-4876-8d1f-6fa45900431c', name: 'Leg', amountInStock: 12}
{id: 'addc65a8-c759-41d8-a18a-89fe446ad484', name: 'Screw', amountInStock: 17}
{id: '831b92b8-677b-42cc-a585-335ea4ccccb6', name: 'Seat', amountInStock: 2}
{id: '6892b98b-9b87-4520-9a9e-7528f1d78cb4', name: 'Table Top', amountInStock: 1}
So you get the point, everytime a visitor order a product it should automatically checks if one of the parts is still in stock. So I was wondering how to subtract from stock.
const increment = (productId: string) => {
const product = productList.find((item: ItemProps) => item.id === productId);
product.articles.forEach((item: any) => {
const test = articleList.find((stock: any) => stock.id === item.id);
});
};
Solution 1:[1]
I have added functions that you asked. It have more loops, better to change data strcture to decrease loops.
parts=[
{id: '0517f083-0e15-4876-8d1f-6fa45900431c', amountRequired: 4},
{id: '831b92b8-677b-42cc-a585-335ea4ccccb6', amountRequired: 1},
{id: 'addc65a8-c759-41d8-a18a-89fe446ad484', amountRequired: 8} ]
allStock=[
{id: '0517f083-0e15-4876-8d1f-6fa45900431c', name: 'Leg', amountInStock: 12},
{id: 'addc65a8-c759-41d8-a18a-89fe446ad484', name: 'Screw', amountInStock: 17},
{id: '831b92b8-677b-42cc-a585-335ea4ccccb6', name: 'Seat', amountInStock: 2},
{id: '6892b98b-9b87-4520-9a9e-7528f1d78cb4', name: 'Table Top', amountInStock: 1} ]
function getStock(id){
return allStock.find(stock=>stock.id===id)
}
// this function return whether stock is enough or not
function isStockAvailable(num){
for(let i=0; i<parts.length;i++){
let part= parts[i]
let stock =getStock(part.id)
if (num * part.amountRequired > stock.amountInStock){
console.log("Stock is not enough for " + num + " item")
return false
}
}
console.log("Stock is enough for " + num + " item")
return true
}
isStockAvailable(1)
isStockAvailable(2)
isStockAvailable(3)
// this function deduct required items from stock and return new stock
function newStock(num){
let newStock = allStock.map(stock=>{
let part= parts.find(p=>p.id===stock.id)
if(part){
return {...stock, amountInStock:stock.amountInStock- num * part.amountRequired }
}else{
return stock
}
})
return newStock
}
console.log("New stock after 2 item ordered: ")
console.log(newStock(2))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yathurshan |
