[英]Getting sum by comparing two arrays
I have 2 arrays, one that contains a list of products, and the other is an orders arrays that contains the orderinfo of multiple purchases.我有 2 个 arrays,一个包含产品列表,另一个是包含多个购买订单信息的订单 arrays。
For example, the products array would look like this:例如, products 数组如下所示:
const products = [
{price: 10, id: 123, ...}
,
...
]
and the orders array would look like:订单数组看起来像:
const orders = [
{
shippinginfo: {...},
orderinfo: {
note: 'a message for the seller',
paymentType: 'visa',
products: [
{
id: 123,
qty: 5
}
]
}
}
]
So my question is, how exactly can i go about summing the price of all the orders in this orders array?所以我的问题是,我究竟如何才能对这个订单数组中所有订单的价格求和?
We can do something like this:我们可以这样做:
const products = [{ price: 10, id: 123 }] const orders = [{ shippinginfo: "", orderinfo: { note: 'a message for the seller', paymentType: 'visa', products: [{ id: 123, qty: 5 }] } }]; let obj = {}; products.forEach((product) => { obj[product.id] = product; }); orders.forEach((order) => { order.orderinfo.products.forEach((product) => { product.price = obj[product.id].price * product.qty; }); }); console.log(orders);
Looping through works.循环播放作品。 To create it more usable added some random products... It will give you sum of the all products in array of orders为了使它更有用,添加了一些随机产品...它将为您提供订单数组中所有产品的总和
const orders = [{
orderinfo: {
note: 'a message for the seller',
paymentType: 'visa',
products: [{
id: 123,
qty: 5
},
{
id: 13,
qty: 2
}]
}
}]
const products = [{
price: 10,
id: 123
},
{
price: 100,
id: 13
},
]
let sum = 0;
orders.forEach(order => {
order.orderinfo.products.forEach(item => {
products.forEach(product => {
if (item.id === product.id) {
sum += product.price * item.qty
}
})
})
});
console.log(sum)
You can Do it Like This:你可以这样做:
const products = [ {price: 10, id: 123} ] const orders = [ { shippinginfo: "", orderinfo: { note: 'a message for the seller', paymentType: 'visa', products: [ { id: 123, qty: 5 } ] } } ] var sum = 0 for (let i = 0;i<orders.length;i++){ var order = orders[i] var orderinfo = order["orderinfo"] var products1 = orderinfo["products"] for (let j = 0;j<products1.length;j++){ var product1 = products1[j] for (let k = 0;k<products.length;k++){ if (products[k]["id"] == product1["id"]){ sum += products[k]["price"]*product1["qty"] } } } } console.log(sum); // 50
const orders = [{
orderinfo: {
note: 'a message for the seller',
paymentType: 'visa',
products: [{
id: 123,
qty: 5
},
{
id: 13,
qty: 2
}]
}
}]
const products = [{
price: 10,
id: 123
},
{
price: 100,
id: 13
},
]
// finds price of order's product and multiply by qty
let sumOfOrders = orders.orderinfo.products.reduce((acc, cur) => acc + (products.find(f => f.id === cur.id)).price * cur.qty)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.