Home > Software engineering >  how to sum all values in a external JSON file
how to sum all values in a external JSON file

Time:10-21

any ideas how to sum all values in my Json file in REACT

I want to sum all values from "complianceChecks"

here is my JSON file:

[
  {
    "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"
  }
]

CodePudding user response:

This is my approach, of course there are many ways to achieve what you want:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related