React:循环遍历数组以求和字段



我的listUserM数组如下所示:

[
{
"Category": "BREAKFAST",
"Name": "Sultana Bran Brekky (Single 70g)",
"CategoryValue": "1breakfast",
"id": "OoUFdwt6G8cbCJgzit6U",
"Quantity": "10",
"Foods": [
{
"label": "Sultana Bran (700g)",
"packingLocation": "AA",
"Weight": ".700",
"Quantity": "0.10",
"value": "SultanaBran(700g)"
},
{
"label": "Chobani Pouch 100g",
"packingLocation": "BB",
"value": "ChobaniPouch100g",
"Weight": "0.100",
"Quantity": "0.50"
}
]
},
{
"Category": "BREAKFAST",
"CategoryValue": "1breakfast",
"Foods": [
{
"Food": "",
"packingLocation": "BB",
"value": "Bacon",
"Weight": "0.400",
"Quantity": 1,
"label": "Bacon"
},
{
"Quantity": "4.00",
"Weight": ".060",
"value": "Eggs",
"packingLocation": "AA",
"label": "Eggs"
}
],
"Name": "Bacon & Eggs",
"id": "FD3Lwb5zjZtdJR5gj3VX",
}
]

我试图做的是循环并计算Foods子数组的总数,该数组与"的packingLocation相匹配;BB";

我一直在使用这个代码,但我无法让它为这个子阵列工作:

var resSetCamperM=listUserM.filter(function(options){
return options.packingLocation == "BB";
}).reduce(function(a,b){
return a+parseFloat(b.Weight * b.Quantity);
},0);

如果我将其更改为:

var resSetCamperM=listUserM[0].Foods.filter(function(options){
return options.packingLocation == "Camper";
}).reduce(function(a,b){
return a+parseFloat(b.Weight * b.Quantity);
},0);

这很有效,但显然只适用于第一个数组。

我如何循环通过Foods数组并计算packingLocation="的总数;BBB";?

您可以使用flatMaplistUserM中移除阵列层

const listUserM = [{
"Category": "BREAKFAST",
"Name": "Sultana Bran Brekky (Single 70g)",
"CategoryValue": "1breakfast",
"id": "OoUFdwt6G8cbCJgzit6U",
"Quantity": "10",
"Foods": [{
"label": "Sultana Bran (700g)",
"packingLocation": "AA",
"Weight": ".700",
"Quantity": "0.10",
"value": "SultanaBran(700g)"
},
{
"label": "Chobani Pouch 100g",
"packingLocation": "BB",
"value": "ChobaniPouch100g",
"Weight": "0.100",
"Quantity": "0.50"
}
]
},
{
"Category": "BREAKFAST",
"CategoryValue": "1breakfast",
"Foods": [{
"Food": "",
"packingLocation": "BB",
"value": "Bacon",
"Weight": "0.400",
"Quantity": 1,
"label": "Bacon"
},
{
"Quantity": "4.00",
"Weight": ".060",
"value": "Eggs",
"packingLocation": "AA",
"label": "Eggs"
}
],
"Name": "Bacon & Eggs",
"id": "FD3Lwb5zjZtdJR5gj3VX",
}
]
var resSetCamperM = listUserM.flatMap(x => x.Quantity ? x.Foods.map(food => ({ ...food,
Quantity: x.Quantity
})) : x.Foods).filter(function(options) {
return options.packingLocation == "BB";
}).reduce(function(a, b) {
return a + parseFloat(b.Weight * b.Quantity);
}, 0);
console.log(resSetCamperM)

function sumByLocation(data, location) {
let sumSoFar = 0
for (const { Foods } of data)
for (const f of Foods)
if (f.packingLocation === location)
sumSoFar += Number(f.Quantity) * Number(f.Weight)
return sumSoFar
}
sumByLocation(dataList, 'BB') // 0.45

最新更新