I am trying to write a function that removes an object from a json file. The json file is formatted with an array of users as such:
{
"users": [
{
"username": "test1",
"answers": [
"Red",
"Blue",
"Yellow",
"Green"
]
},
{
"username": "test2",
"answers": [
"1",
"2",
"3",
"4"
]
}
]
}
The code I wrote is not working for some reason. I want to be able to just pass a variable "test2" into the function and then have that particular user removed from the object, including their answers.
var removeUser = user;
var data = fs.readFileSync('results.json');
var json = JSON.parse(data);
var users = json.users;
delete users.users[user];
fs.writeFileSync('results.json', JSON.stringify(json, null, 2));
You can use filter
to remove the user you do not want
var fs = require('fs');
var removeUser = "test2";
var data = fs.readFileSync('results.json');
var json = JSON.parse(data);
var users = json.users;
json.users = users.filter((user) => { return user.username !== removeUser });
fs.writeFileSync('results.json', JSON.stringify(json, null, 2));
Your users aren't keyed off of name, they're in a numerically indexed array. You have to use delete users.users[1]
, or better yet, use .splice()
.
If you want to delete based on username, you're going to have to loop through.
users.users.forEach((user, index) => {
if (user.username === 'test2') {
users.users.splice(index, 1);
}
});
For anything much more complicated, consider a client-side database like TaffyDB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With