任何想法如何在 REACT 中對我的 Json 檔案中的所有值求和
我想總結“complianceChecks”中的所有值
這是我的 JSON 檔案:
[
{
"propertyId": 1,
"name": "The Shard",
"complianceChecks": [
{ "electrical": 2500.5 },
{ "structural": 7250 }
],
"nextCheckOn": "2021-03-04T12:13:14Z"
},
{
"propertyId": 2,
"name": "The Gherkin",
"complianceChecks": [
{ "fire": 1000 },
{ "electrical": 3000.25 }
],
"nextCheckOn": "2021-04-21"
},
{
"propertyId": 3,
"name": "The Walkie Talkie",
"complianceChecks": [
{ "fire": 1500.25 },
{ "structural": 7000 }
],
"nextCheckOn": "2021-09-20"
}
]
uj5u.com熱心網友回復:
這是我的方法,當然有很多方法可以實作您想要的:
const yourArray = [
{
propertyId: 1,
name: 'The Shard',
complianceChecks: [{ electrical: 2500.5 }, { structural: 7250 }],
nextCheckOn: '2021-03-04T12:13:14Z',
},
{
propertyId: 2,
name: 'The Gherkin',
complianceChecks: [{ fire: 1000 }, { electrical: 3000.25 }],
nextCheckOn: '2021-04-21',
},
{
propertyId: 3,
name: 'The Walkie Talkie',
complianceChecks: [{ fire: 1500.25 }, { structural: 7000 }],
nextCheckOn: '2021-09-20',
},
];
const total = yourArray.reduce((total, el) => {
el.complianceChecks.forEach((value) => {
const keys = Object.keys(value);
total = value[keys[0]];
});
return total;
}, 0);
console.log('Total: ' total);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/328578.html
上一篇:JQ搜索正則運算式
