【问题标题】:How to sum all values in an external JSON file如何对外部 JSON 文件中的所有值求和
【发布时间】:2021-12-07 16:41:39
【问题描述】:

如何在 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"
  }
]



【问题讨论】:

    标签: reactjs json


    【解决方案1】:

    这是我的方法,但当然有很多方法可以实现你想要的:

    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);

    【讨论】:

    • 你是神!谢谢
    猜你喜欢
    • 2022-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2012-12-13
    • 1970-01-01
    相关资源
    最近更新 更多