我想qty
從資料中獲取值的總和。我試過了,但我只得到陣列中第一項的總數量。
我只想要10
下面的結果 (4 5 0 1)
let xyz = [{
catid: '1',
catName: 'abc',
product: [{
id: 1,
qty: 4,
},
{
id: 2,
qty: 5,
}
]
},
{
catid: '2',
catName: 'efg',
product: [{
id: 3,
qty: 0,
},
{
id: 4,
qty: 1,
}
]
}
]
uj5u.com熱心網友回復:
要執行您需要的操作,您可以使用reduce()
. 您將需要嵌套兩個reduce()
呼叫,一個qty
對每個產品的內部求和,然后另一個對所有產品的總和求和:
let xyz = [ {catid: "1", catName: "abc", product: [{ id: 1, qty: 4 }, { id: 2, qty: 5 }]},{ catid: "2", catName: "efg", product: [{ id: 3, qty: 0 },{ id: 4, qty: 1 }]}];
var total = xyz.reduce((t0, o) => t0 o.product.reduce((t1, prod) => t1 prod.qty, 0), 0);
console.log(total);
uj5u.com熱心網友回復:
2 forEach 的更丑陋的方式..
let xyz = [{
catid: '1',
catName: 'abc',
product: [{
id: 1,
qty: 4,
},
{
id: 2,
qty: 5,
}
]
},
{
catid: '2',
catName: 'efg',
product: [{
id: 3,
qty: 0,
},
{
id: 4,
qty: 1,
}
]
}
]
let sum = 0;
xyz.forEach(element => {
element.product.forEach(product => {
sum = product['qty'];
});
});
console.log(sum);
uj5u.com熱心網友回復:
let totalqTy = 0;
xyz.forEach(o => {
totalqTy = o.product.map(p => p.qty).reduce(((previousValue, currentValue) => previousValue currentValue));
});
uj5u.com熱心網友回復:
你需要一個嵌套回圈。Array#reduce可以解決問題。
let xyz = [{
catid: '1',
catName: 'abc',
product: [{
id: 1,
qty: 4,
},
{
id: 2,
qty: 5,
}
]
},
{
catid: '2',
catName: 'efg',
product: [{
id: 3,
qty: 0,
},
{
id: 4,
qty: 1,
}
]
}
]
const quantity = (input) =>
input.reduce((p, { product }) =>
p product.reduce((p, { qty }) => p qty, 0), 0)
console.log(quantity(xyz)) // 10
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/508299.html
標籤:javascript 反应 数组 jsx
上一篇:WPF-將命令系結到串列框專案?