Concatenate device readings in JSON object - Javascript

Viewed 81

I have devices in the field that send readings in the format of sessions to a database. These sessions have a start time, an end time and a session time value (indicating how long the session was). When I call the database (MySQL), it sends me back each row with the start, end and duration times for each session for the device, in a defined month that I request (for example I can send it December 2018 for all sessions in that month). This is what the database send back to me:

DeviceUID: xxx-xxx-xxx
Start Date: 2018-12-10T17:12:31.000Z
End Date: 2018-12-10T21:32:12.000Z <- I convert this to YY:MM:DD HH:mm:ss
Duration: 16237312                 <- This is a value in seconds

What I want to do, is to create a JSON object that has an entry for each day of the month, and a value for the total duration of sessions on that day. Note that each day should have ONLY ONE entry, that sums all the duration for that day. See below:

{
  "2018-12-01": "02:12:54",   <-- duration in HH:mm:ss
  "2018-12-02": "01:43:52",
  ...
}

The code I currently have can do a for each loop through the rows I receive from the MySQL database, but I'm not sure how to approach the summation of durations per day and how to get it into a JSON properly. Could you please help me out?

NOTE: I take the day as the end date only. Thus, if a session started on 2018-12-01 and ended on 2018-12-02, I will add the session's duration to 2018-12-02's value only.

1 Answers

I'm not sure what your code base looks like, but these are the steps that you need to take:

  • Name the object data, and name the first key in the object date.

  • Name a second field called duration.

  • Set the value of date to the date that the user has requested.

  • In your for each that goes through each device, calculate the difference between your end time and start time.

I tried my best to understand your question, and from what I understand, you want the total time of all devices while in a session.

So:

  • Initialize duration by setting it to 0.
  • Then, in the for each, add the difference between your end time and start time to duration.
  • Return the object to the user.

Hope this helps!

Related