0

I have a function in React that gets a response fron API. Response is a JSON-file which is always consist of slot1 : {..}, slot2 : {...}, ... slot13: {...}. My code to handle it is:

async function fetchOperationsNumChart(pk=props.activeID) {
const response = await OperationsService.getTodayOpsChart(pk)
  if (response) {
    setOperationsNumChart(
      [
        createData(response.data.slot1.time, response.data.slot1.operations),
        createData(response.data.slot2.time, response.data.slot2.operations),
        createData(response.data.slot3.time, response.data.slot3.operations),
        createData(response.data.slot4.time, response.data.slot4.operations),
        createData(response.data.slot5.time, response.data.slot5.operations),
        createData(response.data.slot6.time, response.data.slot6.operations),
        createData(response.data.slot7.time, response.data.slot7.operations),
        createData(response.data.slot8.time, response.data.slot8.operations),
        createData(response.data.slot9.time, response.data.slot9.operations),
        createData(response.data.slot10.time, response.data.slot10.operations),
        createData(response.data.slot11.time, response.data.slot11.operations),
        createData(response.data.slot12.time, response.data.slot12.operations),
      ]
    )
  }
}

I believe that it's possible to optimize such code using "for" cycle. But constructions like response.data.slot${i}.time after for (let i = 1; i <= 13: i++) won't work. How to reduce the code above using for?

Ivan
  • 43
  • 5

0 Answers0