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

Bring in items and then go through each one

I'm curious if there's a way to loop through imported objects? import { Row, Col, Form, FormItem, Icon, Input, Tooltip, Image, Button, Dialog } from 'element-ui' objects.forEach(object => { // do something here }) When I have a ...

What is the best method for choosing the next item with jQuery?

I am facing an issue while trying to apply some design on the next element. The error message that I am encountering is: Error: Syntax error, unrecognized expression: [object Object] > label Below are my selections for browsing by category: BROWSE BY ...

Using AngularJS to create a form and showcase JSON information

My code is below: PizzaStore.html: <!DOCTYPE html> <html ng-app="PizzaApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Delicious pizza for all!</title> ...

Prevent the Spread of an Event for a Particular Controller

tl;dr Summary Develop a function that is able to handle a specific event on multiple elements within a hierarchy. The function should execute when the event is triggered on the first element reached during bubbling, but should not continue executing or re ...

Responsive Fullscreen Bootstrap Panel with Highcharts

One issue I'm facing is with my (bootstrap) panels that contain Highcharts charts and I want them to show fullscreen without losing their aspect ratio. The problem is that the size of the Highcharts does not adjust when going into full-screen mode. Is ...

Leverage JavaScript variables within JSON objects

I have a JavaScript variable that I want to use in a JSON format. var add = mixItems[i][0] + "," + mixItems[i][1]; jQuery.getJSON("wp-content/plugins/proteinmixer/php/addtocart.php" , function(data){ }); Here is the PHP code: require_once('../../.. ...

Issues with Angular 2 and Deserialization of .NET List<T>

I'm encountering issues when trying to deserialize a .NET List into an Angular 2 array. An error keeps popping up: ERROR Error: Cannot find a differ supporting object...NgFor only supports binding to Iterables such as Arrays. I've looked around ...

Issue encountered - Attempting to provide an object as input parameter to puppeteer function was unsuccessful

Encountering an error when attempting to pass a simple object into an asynchronous function that utilizes puppeteer. The specific error message is: (node:4000) UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: userInfo is not def ...

The retrieval process is unable to receive a response from the server

Question: I am encountering an issue with the fetch API in the client-side code. Here is the snippet of the code: window.fetch('/signup', { method: 'post', headers: { 'Content-Type': 'application/x-www-form-urlen ...

Managing bidirectional references with polymorphic types and JSON: A guide

Question: Is there a solution for managing bidirectional references with polymorphic types in Jackson while also using @JsonTypeInfo? The note at the bottom of this page suggests it was not possible in 2010 with Jackson v1.6.0, but I am curious if any upda ...

Encountering an issue where props are receiving a value of undefined within a component that is

After receiving a JSON response from getStaticProps, I double-checked the data by logging it in getStaticProps. The fetch functionality is working smoothly as I am successfully retrieving the expected response from the API. import Layout from '../comp ...

Trigger jQuery when a breakpoint has been met

I am working on a responsive design that has multiple breakpoints. Within the content, some block dimensions are calculated using jQuery. Whenever the viewport changes, these dimensions also change and therefore the calculation needs to be re-run. How can ...

The 'load()' event method in jQuery does not function properly within the 'ready()' event method on mobile browsers

After testing on Firefox mobile and Chrome mobile browsers, I found that my code works perfectly on computer browsers. Below is the code I have inside the ready() and load() event methods: $(document).ready(function(){ $(window).on('load hashchan ...

Picture is unavailable for viewing - (Express, Pugjs)

I'm having trouble getting an image to display on my page using a pug template. Despite following the setup and files correctly, the image still isn't showing up. Here is what I have: index.js app.use('/images', express.static(path.r ...

An issue has arisen while parsing a JSON array that is set up to accept

My code works perfectly fine when I provide a single data element in my JSON file. However, when I input an array of elements, it starts displaying "undefined" on the client side. Below is the snippet of my server-side code: var app = require('expres ...

Could it be that v-show does not function properly on elements that are not dynamic

I'm not experienced in web development and this is my first attempt at using a web framework. The framework I am currently learning is vue.js version 3. My goal: I want to create 4 app instances (nav, defaultApp, bootstrapApp, vueApp). When I select ...

GATSBY: Error: Unable to find the specified property 'includes' within an undefined value

I'm struggling to figure out how to properly filter images in my portfolio website as discussed in this post… Every time I attempt it, I encounter the following error: "TypeError: Cannot read property 'includes' of undefined" D ...

Add a container element resembling a div inside a table without implementing the table layout

I am working with a table that is rendered by DataTable, and I have the requirement to dynamically append new elements inside the table like this: The dark grey area represents the new DOM elements that need to be inserted dynamically. The first row cont ...

The Wordpress plugin's Ajax function is giving back a response value of zero

I'm facing an issue where I am attempting to send AJAX data to my wordpress table, but the response I receive from my PHP script is always a 0. This problem arises specifically on the admin side of things. Can anyone provide assistance? Furthermore, ...

How to add a subtle entrance animation to text (demonstration provided)

Apologies for the brevity, but I could really use some assistance with replicating an effect showcased on this particular website: My understanding is that a "fadeIn" can be achieved using jQuery, however, I am at a loss as to how to implement the 3D effe ...