0

my JSON file

[
  {
    "id": 1,
    "task": "go dancing",
    "status": false
  },
  {
    "id": 2,
    "task": "Walk",
    "status": false
  }
]

i got really stuck on my OOP, i tried to find the Property Status in my json and i want to update the property boolean tp be true from false

here is my code

static completed(input) {
    const data = Model.getdAll(); // get './data.json' local host, 
    for (let i = 0; i < data.length; i++) {
      if(data[i].id == input){
        data[i].status = true
        Model.writeFile(data);
        return data
      }
    }
  }

when i console.log( on that static method , it was like this

here is my writefile static method

static writeFile(data) {
    return fs.writeFileSync("./data.json", JSON.stringify(data, null, 2) , 'utf8');
  }

//when i console.log( on that static method , it was like this

Model { id: 4, task: 'going to gym', status: true }

when i write file inside that for loop and after the forloop the real data is not changed and that status still false

4
  • Can you provide some of the data.json contents? Commented Feb 13, 2019 at 15:42
  • just updated , look that @kemicofa Commented Feb 13, 2019 at 15:44
  • So, does the writeFileSync update the data.json correctly or is it simply the data being sent back that isn't correct? Commented Feb 13, 2019 at 15:51
  • Are you allowed to write to the file? So basically; does writeFileSync return an error? Commented Feb 13, 2019 at 16:03

1 Answer 1

1

Consider using Array#find. Object will be a reference to the object inside of the data array, so changing it will also change what's inside of data.

const Model = {
  getdAll: function(){ return [{"id":1,"task":"go dancing","status":!1},{"id":2,"task":"Walk","status":!1}] },
  writeFile: function(data){ console.log(JSON.stringify(data, null, 2)) }
}

function completed(input){
    const data = Model.getdAll(); // get './data.json' local host,
    const object = data.find(({id})=>id === input);
    
    if(!object) throw new Error("Object not found");
    object.status = true;
    Model.writeFile(data);
    return data;
}

const res = completed(1);

You should also keep in mind that fs.writeFileSync does not return anything, but it does throw an error if it failed.

Consider, wrapping it in a try/catch:

static writeFile(data) {
   try {
      fs.writeFileSync("./data.json", JSON.stringify(data, null, 2) , 'utf8');
   }
   catch(e){
      console.warn(e.message);
   }
}
Sign up to request clarification or add additional context in comments.

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.