My goal is to update an array of objects only after all the necessary checks have passed. I have one array of objects representing all the articles and another array of objects representing the available stock.
I want to make sure that all the articles are in stock before updating the stock array. Here is the code I currently have:
const articles = [{
"id": "1",
"quantity": "4"
}, {
"id": "2",
"quantity": "8"
}, {
"id": "4",
"quantity": "1"
}];
let stock = [
{
"id": "1",
"stock": "6"
},
{
"id": "2",
"stock": "6"
},
{
"id": "3",
"stock": "2"
},
{
"id": "4",
"stock": "2"
}
];
articles.map(article => {
stock.map(item => {
if(item.id === article.id){
if(article.quantity <= item.stock){
item.stock = item.stock - article.quantity;
} else {
console.log('error');
throw error;
}
}
});
});
The issue with this solution is that it updates the stock for id = 1
even when the stock for id = 2
is not enough. I want to ensure that all the articles are in stock in sufficient quantity before updating them in the stock array. Ideally, the stock array should be updated as follows:
stock = [
{
"id": "1",
"stock": "2"
},
{
"id": "2",
"stock": "6"
},
{
"id": "3",
"stock": "2"
},
{
"id": "4",
"stock": "2"
}
];
Can anyone provide suggestions on how I can resolve this issue?