Help with JS - join results together

Hi, need a bit of help with JS. I have a bit a workflow that does the following:

  • Triggers based on schedule
  • Gets a list of meters and last updated from the database
  • Loops through an API providing meter and last update date to download latest data
  • Stores results in array ( I get an array of 0 to 4 with the results in)
  • Transforms the results into an array that matches the table format (meter, date_time, reading, Primary key)
  • upsets into table in database

But my JS is pants

The following code returns a result of only the last meter, or rather it will keep overwriting 'result'. How do I join the results together to give a longer set that can be upserted together.

Or preferably push/call dbInsert with the 'result' on each loop which will keep my upserts smaller.

for (let i=0; i<meterAPI.data.length; i++){

const result = meterAPI.data[i].readings.map(reading => ({
  meter: meterAPI.data[i].emigId,
  date_time: reading.ts,
  reading: reading.importEnergy.value,
  fakepk: meterAPI.data[i].emigId + "-" + reading.ts
}));

return result;
}

Thanks Dave

You can use flatMap. flatMap will take the array of results you return with .map and flatten it. so for example an array of [[1,2],[3,4]] will turn into [1,2,3,4].

const allResults = meterAPI.data.flatMap(meter => 
  meter.readings.map(reading => ({
    meter: meter.emigId,
    date_time: reading.ts,
    reading: reading.importEnergy.value,
    fakepk: `${meter.emigId}-${reading.ts}`
  }))
);

The result will be a single array containing all the results which you can then use to upsert.

Awesome thanks, that does the job.

Its hard when you don't know a function exists.

1 Like