Reputation: 303
I have problem for makings some calculation for two values in two object arrays and get one array of the result,
if the _id is found in orders less the qty from the same _id in the Stocks if keep the qty as it is ..
Array 1 # orders
[
{
"_id": "5e64cfb59726d72129e78aee",
"qty": 10
},
{
"_id": "5e64d0fe9978d443af7db86c",
"qty": 14
}
]
Array 2 # stocks
{
"_id": "5e64d0fe9978d443af7db86c",
"qty": 600
},
{
"_id": "5e64cfb59726d72129e78aee",
"qty": 60
},
{
"_id": "5e64cfb59726d72129e78ab5",
"qty": 650
}
needed output :
{
"_id": "5e64cfb59726d72129e78aee",
"qty": 50
},
{
"_id": "5e64d0fe9978d443af7db86c",
"qty": 586
},
{
"_id": "5e64cfb59726d72129e78ab5",
"qty": 650
}
Upvotes: 0
Views: 134
Reputation: 3236
You have to iterate on your arrays:
orders.foreach(order => {
let stock = stocks.find(stock => stock._id === order._id);
if (stock) {
stock.qty -= order.qty
}
});
console.log('new stocks', stocks);
Upvotes: 0
Reputation: 7770
Something like this should do
const stocks = [{
"_id": "5e64d0fe9978d443af7db86c",
"qty": 600
},
{
"_id": "5e64cfb59726d72129e78aee",
"qty": 60
},
{
"_id": "5e64cfb59726d72129e78ab5",
"qty": 650
}
];
const orders = [{
"_id": "5e64cfb59726d72129e78aee",
"qty": 10
},
{
"_id": "5e64d0fe9978d443af7db86c",
"qty": 14
}
];
const result = stocks.map(stock => {
const foundRec = orders.find(order => order._id === stock._id);
if (foundRec) {
return {
"_id": stock._id,
"qty": stock.qty - foundRec.qty
};
}
return stock;
});
console.log(result);
Upvotes: 1