skip to Main Content

I have this JSON array that Zabbix retrieves and each object has the keys "startTime" and "endTime" which are date-time strings in the format of "DD-MM-YYYY HH:mm:ss".

Using Javascript, I’m trying to add a new key to each object in the array.
The new key is called "execTime" and it should have a value equal to the difference between "endTime" and "startTime" in seconds.

Input JSON sample:

[
    {
    "endTime": "02-02-2024 10:10:20",
    "startTime": "02-02-2024 10:10:10",
    },
    {
    (...)
    }
]

Expected output JSON:

[
    {
    "endTime": "02-02-2024 10:10:20",
    "startTime": "02-02-2024 10:10:10",
    "execTime": 10
    },
    {
    (...)
    }
]

For that, I was trying to use the following script.

function (value) {
    const jsonValue = JSON.parse(value);

    for (var i = 0; i < jsonValue.length; i++) {
      const startDate = new Date(jsonValue[i].startTime);
      const endDate = new Date(jsonValue[i].endTime);

      const execTime = ( endDate.getTime() - startDate.getTime() ) / 1000;
      if ( execTime < 0 ) { var execTime = 0; }
      jsonValue[i].execTime = execTime;
    };

    return jsonValue;
}

The problem is that the return value is this:

[object Object],[object Object],[object Object], (...)

Any thoughts on this?

2

Answers


  1. return JSON.stringify(jsonValue);

    // Convert the result back to a JSON-formatted string

    Login or Signup to reply.
  2. There is no need to JSON.parse your data you could just access the properties directly. Also avoid using const to declare your variables if you are gonna change their value later on.

    var data = [
        {
        "endTime": "02-02-2024 10:10:20",
        "startTime": "02-02-2024 10:10:10",
        },
        {
        "endTime": "02-02-2024 10:09:40",
        "startTime": "02-02-2024 10:10:10",
        },
        {
        "endTime": "02-02-2024 10:10:30",
        "startTime": "02-02-2024 10:10:10",
        },
        {
        "endTime": "02-02-2024 10:10:50",
        "startTime": "02-02-2024 10:10:10",
        }
    ];
    
    function insertExecTime(data) {
        for (var i = 0; i < data.length; i++) {
          let startDate = new Date(data[i].startTime);
          let endDate = new Date(data[i].endTime);
    
          let execTime = ( endDate.getTime() - startDate.getTime() ) / 1000
          if ( execTime < 0 ) { 
           execTime = 0; 
          }
          data[i].execTime = execTime;
        };
    }
    
    insertExecTime(data);
    console.log(data);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search