Transform the JSON data to generate a fresh JSON output

I'm seeking help to develop a script that generates JSON data based on specific conditions. As of now, I believe my logic is correct.

Any assistance would be greatly appreciated.

CURRENT ISSUES:

  • [resolved]I am unable to determine why the duration consistently returns as 0
  • [resolved]Addressing how to set the max/min
  • Solving the issue of managing back-to-back excursions of different types ("hot" ⇒ "cold" or "cold" ⇒ "hot")

This is the expected appearance of each new object

  let current_excursion = {
      'device_sensor' : '',
      'start_at' : [],
      'stop_at' : 0,
      'duration' : 0,
      'type': '',
      'max/min':0
}

device_sensor The sId where this excursion was detected.

start_at The timestamp when the temperature first goes out of range in ISO_8601 format.

stop_at The timestamp when the temperature returns to the normal range in ISO_8601 format.

duration The total time in seconds the temperature stayed out of range.

type Either "hot" or "cold", depending on the type of the excursion.

max/min The extreme temperature for the excursion. For a "hot" excursion, this will be the maximum; for a "cold" excursion, it will be the minimum.

A temperature excursion event begins when the temperature goes out of range and ends when it gets back within range. For a "hot" excursion, this occurs when the temperature exceeds 8°C, and for a "cold" excursion, it happens when the temperature falls below 2°C. If two excursions of different types occur consecutively ("hot" ⇒ "cold" or "cold" ⇒ "hot"), consider the midpoint between the timestamps as the end of the first excursion and the start of the second one.

If an excursion is ongoing at the final temperature reading, conclude the excursion at that point (with a duration of 0).

Here is the link to access the test data: Test Case Data

Below is what I have written so far:

const tempTypeTernary = (num) =>{
    if(num < 2){
      return 'cold'
    } else if(num > 8){
      return 'hot'
    }
}

const excursion_duration = (x,y) =>{
  let start = new Date(x) / 1000
  let end =  new Date(y) / 1000

  return end - start
}

const reset_excursion = (obj) => {
  Object.keys(obj).map(key => {
    if (obj[key] instanceof Array) obj[key] = []
    else obj[key] = ''
  })
}


const list_excursion = (array) =>{

  let result = [];
  let max_min_excursion = 0;
  let current_excursion = {
      'device_sensor' : '',
      'start_at' : [],
      'stop_at' : 0,
      'duration' : 0,
      'type': '',
      'max/min':0
}

  for(let k = 0; k < array.length;k++){

    if( array[k]['tmp'] < 2 || array[k]['tmp'] > 8){

      current_excursion['device_sensor'] = array[k]['sId'];
      current_excursion['start_at'] = [new Date(array[k]['time']).toISOString(),array[k]['time']];
      current_excursion['type'] =  tempTypeTernary(array[k]['tmp']);

      if( array[k]['tmp'] > 2 || array[k]['tmp'] < 8){
        current_excursion['stop_at'] = new Date(array[k]['time']).toISOString();
        current_excursion['duration'] = excursion_duration(current_excursion['start_at'][1],array[k]['time'])
          }
          result.push(current_excursion)
          reset_excursion(current_excursion)
      }


  }
  return result
}

list_excursion(json)

Answer №1

Feel free to take a bold step and give your opinion just by looking at the code; here's a suggestion for you:

const determineTemperatureType = (num) => {
    if(num < 2){
      return 'cold';
    } else if(num > 8){
      return 'hot';
    }
}

const calculateExcursionDuration = (start, end) => {
  let startTime = new Date(start).getTime() / 1000;
  let endTime =  new Date(end).getTime() / 1000;

  return endTime - startTime;
}

const resetExcursionObject = (obj) => { 
  Object.keys(obj).map(key => {
    obj[key] = Array.isArray(obj[key]) ? [] : '';
  });
}

const parseExcursionList = (array) => {
  let result = [];
  let currentExcursion = {
    'device_sensor': '',
    'start_at': [],
    'stop_at': 0,
    'duration': 0,
    'type': '',
    'max/min': 0
  };

  for(let i = 0; i < array.length; i++) {
    if(array[i]['tmp'] < 2 || array[i]['tmp'] > 8)
    {
      if (currentExcursion['type'] === '') {
        currentExcursion['device_sensor'] = array[i]['sId'];
        currentExcursion['start_at'] = [new Date(array[i]['time']).toISOString(), array[i]['time']];
        currentExcursion['type'] = determineTemperatureType(array[i]['tmp']);
      }
    }
    else {
      if(currentExcursion['type'] !== '') {
        currentExcursion['stop_at'] = new Date(array[i]['time']).toISOString();
        currentExcursion['duration'] = calculateExcursionDuration(currentExcursion['start_at'][1], array[i]['time']);

        result.push(currentExcursion);
        resetExcursionObject(currentExcursion);
      }
    }
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Exploring ways to create and save content in a different root folder within a nodejs project using my

In the process of developing my npm module, I am faced with the task of creating or writing a file in either the root directory or a specific folder within the nodejs project that will be utilizing my module. This includes users who will be implementing my ...

Unable to See Success Notification on First Attempt

I am facing an issue with displaying a message when adding a new record. The first time I add a record, the message shows up correctly. However, if I try to add another record, the message does not appear even though the record is added successfully. Here ...

Substitute placeholders in array with information using a loop

I have a question regarding implementing an autosort feature in JavaScript. I want my page to automatically sort data rows based on different time intervals selected by the user through checkboxes. The data updates every 3 seconds, and the autosort functio ...

Preserving color output while executing commands in NodeJS

My Grunt task involves shelling out via node to run "composer install". var done = this.async(); var exec = require('child_process').exec; var composer = exec( 'php bin/composer.phar install', function(error, stdout, stderr) { ...

React Material UI unselect

I have been exploring a MUI select field implementation using this example as a guide. While I was able to make the code work, there are a few issues that I encountered. One of them is the inability to deselect a value once it has been selected. Additional ...

Error message: The Slick Carousal encountered an unexpected problem - TypeError:undefined is not a function

I'm having an issue with a script for a Slick Carousel inside of some Ajax Tabs. I keep encountering the Uncaught TypeError: undefined is not a function error, but I'm unsure what exactly it's pointing to. $(document).ready(function(){ ...

Issues have been encountered with Angular 5 when trying to make required form fields work properly

Just created my first Angular app using Angular 5! Currently following the documentation at: https://angular.io/guide/form-validation. Below is the form I have set up: <form class="form-container"> <mat-form-field> <input matInput pl ...

Why is the Get request for fetching data not returning multiple parameters, but only returning a single one in Vuex?

I am trying to fetch and visualize a list of data with a GET request while passing two parameters. However, I am encountering an error 400 when passing both parameters, but it works fine when passing just one. Link to code This is the non-working code: a ...

Enhance videojs player source with personalized headers

Currently, I have a backend API running on Express that manages a streaming video m3u8 file. The endpoint for this file is: http://localhost:3000/api/stream.m3u8 It is important to note that access to this endpoint requires a valid user token. router r ...

The development server fails to respond when initializing a new project following the NextJs documentation for an empty project

After consulting the NextJs framework documentation, I meticulously followed the setup instructions to initialize an empty project : mkdir hello-next cd hello-next npm init -y npm install --save react react-dom next mkdir pages Subsequently, I included t ...

Having difficulty executing a Java EE Program demo

Just stepping into the world of Java with a non-web development background and recently dived into a Java EE application named TicketMonster provided by JBoss (https://github.com/jboss-developer/ticket-monster). The initial steps included downloading the ...

The AJAX request encountered an error due to an Unexpected End of JSON Input

My AJAX code is encountering an error message. parsererror (index):75 SyntaxError: Unexpected end of JSON input at parse (<anonymous>) at Nb (jquery.min.js:4) at A (jquery.min.js:4) at XMLHttpRequest.<anonymous> (jquery.min.js: ...

Preserving classes in JQuery after making AJAX requests

Before we proceed, it's important to note that I am unable to modify any of the existing calls, code, or functions. This means I must come up with a workaround solution. So, here's the situation: I have a form containing various fields and a dro ...

Import data from a distant file into a node Buffer within the web browser

Currently, I am utilizing browserify to utilize this particular package within the browser. Specifically, I have developed a phonegap application that retrieves .fsc files from the server. The code snippet looks like this: var reader = new FileReader( ...

A fresh checkbox was added to the page using Jquery Switchery to disable it

I'm having trouble disabling the Switchery checkbox. When I try to disable it, another Switchery checkbox appears on the page along with the one I previously defined: <div class="form-group"> <label class="col-md-2"> ...

Aggregate array based on specified criteria in ReactJS

Let's consider the following array data: array = [ { id: 1, count: 0.5 cost: 100 user: {id: 1, name: "John 1"}, type: {id: 1, name: "T1"}, period: {id: 1, name: "2021"} ...

Modify jQuery to update the background image of a data attribute when hovering over it

Something seems to be off with this topic. I am attempting to hover over a link and change the background image of a div element. The goal is to always display a different picture based on what is set in the data-rhomboid-img attribute. <div id="img- ...

Having trouble sending the request body via next-http-proxy-middleware

Recently, I've been attempting to develop a frontend using nextjs that communicates with a Java backend. To achieve this, I'm utilizing the npm package next-http-proxy-middleware. However, it seems like either my request body is getting lost in t ...

Having trouble accessing object properties fetched via API, receiving the error message "TypeError: Cannot read property '' of undefined" in Next.js with JavaScript

Encountering a unique issue specific to NextJs. Fetching data from an API using a custom hook and receiving an array of objects as the result. Successfully logging the entire result (array of objects). const myMovieGenreObjects = useFetchNavBarCategories( ...

Having trouble releasing the package on npm platform

I'm facing difficulties in publishing a public package to npm. Despite creating an organization, I'm unable to figure out how to add a new package. Any assistance on this matter would be greatly appreciated. ...