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
return JSON.stringify(jsonValue);
// Convert the result back to a JSON-formatted string
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.