I want my json-file to be edited when the given time/date is in the past. I've tried delete termine[0] but this does not delete the part of the file.
My json-file
[{
"datum": "2020-10-10T10:00:00",
"event": "..."
},
{
"datum": "2021-10-10T10:00:00",
"event": "..."
},...
]
My Code
let termine = JSON.parse(fs.readFileSync("/home/pi/NeonBot/termine.json", "utf8"))
var now = new Date();
var date = termine[0].datum
date = new Date(date)
do {
delete termine[0]
console.log(`Deleted Event`)
} while (date < now)
CodePudding user response:
You have an infinite loop, because you never update date
in the loop.
You should also check the condition before deleting, not after.
while (new Date(termine[0].datum_) < now) {
delete termine[0];
console.log("Deleted Event");
}
Instead of deleting one element at a time, find the index of the first element to keep, then remove all the ones before it with splice
.
let index = termine.findIndex(event => new Date(event.datum) >= now);
if (index > 0) {
termine.splice(0, index);
}
fs.writeFileSync("/home/pi/NeonBot/termine.json", JSON.stringify(termine), "utf8");