Reputation: 607
I need to be able to remove a specific object from my json file so I can renew the time.
At the moment I've tried to use a for loop to find the right one but this doesn't work and it just adds a new object without removing the old one.
How would you be able to remove the old object from the json file?
nodejs
function updateTime(id,name) {
var newServer = {
"id": id,
"name": name,
"time": new Date()
}
var id = id;
fs.readFile('servers.json', function (err, data) {
var json = JSON.parse(data);
json.push(newServer);
// for loop to check if the server has already been added in the json file.
for(var i = 0; i < json.length; i++) {
var id = json[i].id;
delete json[i][id];
console.log("removed " + json[i][id]);
// return;
}
fs.writeFile("servers.json", JSON.stringify(json, null, 4), function (err) {
if (err) throw err;
console.log('Saved new server!');
});
});
}
json file
[
{
"id": "728374892403228752",
"name": "test2",
"time": "2020-07-02T23:06:59.889Z"
},
{
"id": "725475771321155605",
"name": "test server",
"time": "2020-07-02T23:06:59.889Z"
}
]
Upvotes: 0
Views: 2724
Reputation: 1178
You are overwriting the id in the global scope, so you want to make sure they the array of objects has all unique ids
function updateTime(id,name) {
var newServer = {
"id": id,
"name": name,
"time": new Date()
}
fs.readFile('servers.json', function (err, data) {
var json = JSON.parse(data);
json.push(newServer);
// for loop to check if the server has already been added in the json file.
var duplicates = 0
var newJson = []
// count the duplicates to make sure there is only one of that object with the id
for(var i = 0; i < json.length; i++) {
if(json[i].id === id) {
duplicates++
}
if(duplicates <=1) {
newJson.push(json[i])
}
}
fs.writeFile("servers.json", JSON.stringify(newJson, null, 4), function (err) {
if (err) throw err;
console.log('Saved new server!');
});
});
}
Upvotes: 0
Reputation: 56
Appears that the for-loop would remove the id
property from each object.
If you'd like to remove the object containing a specific id, you could use the filter
method on Array
.
json.filter(entry => entry.id !== specificId);
Upvotes: 1
Reputation: 1648
If you need to remove spesific objects in an array you can filter them out. Consider following.
fs.readFile('servers.json', function (err, data) {
var json = JSON.parse(data);
json.push(newServer);
// So you need to have an id of an object to remove
// so lets say that it's 728374892403228752 this number.
var idToRemove = 728374892403228752;
// So this will filter out that object with an id of `idToRemove`
json = json.filter(child => parseInt(child.id) !== idToRemove);
// after this you can do your fileWrite again :)
//...
}
Upvotes: 1