4

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));

3 Answers 3

8

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));
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1

This is one of the ways to remove the task or data from the todos or database I will support like this more as a student

const loadTask = () => {
  try {
    const dataBuffer = fs.readFileSync(filePath);
    const dataJson = dataBuffer.toString();
    return JSON.parse(dataJson);
  } catch (error) {
    return [];
  }
};

const removeTask = (taskToRemove) => {
  let tasks = loadTask();
  const filteredTasks = tasks.filter((task) => task.task !== taskToRemove);

  if (tasks.length === filteredTasks.length) {
    console.log(`Task "${taskToRemove}" not found.`);
  } else {
    saveTasks(filteredTasks);
    console.log(`Task "${taskToRemove}" removed successfully!`);
  }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.