0

How to replace old json object using NodeJS with a new updated object ?

Right now when i update the json file it saves the new data with the old one.

JSON :

[ {
    "id": 1,
    "name": "Sven",
    "phone": "123123"
  },
  {
    "id": 2,
    "name": "Martin",
    "phone": "2342342"
  } ]

Here is my code :

var operation = POST.operation; // POST request comes with operation = update/insert/delete


        if (operation == 'update') {
            fs.readFile("file.json", "utf8", function (err, data) {

                var jsonFileArr = [];
                jsonFileArr = JSON.parse(data); //Parse the data from JSON file                    
                var haveId = jsonFileArr.some(function (obj){ // Checks if the POST request have the same id as JSON file
                    return obj.id == POST.id;
                })

                if (haveId) {  // if true

                    var updateData = []; // Array with POST data
                    updateData.push({
                        id: POST.id,
                        name: POST.name,
                        phone: POST.phone,
                    })
                    jsonFileArr.push(updateData);
                    var newUsers = JSON.stringify(jsonFileArr);
                    fs.writeFile("file.json", newUsers, "utf8");
                    console.log(err);
                }
            })                
        }

I should probably use delete object but how can i specify what object should be removed ?

So when i update data with id 1 it would delete the old id / Name / phone and write the new data.

1 Answer 1

2

My assumption base on your question is that you have multiple objects in one file. So the easy way to work around this would be to

      if (operation == 'update') {
        fs.readFile("file.json", "utf8", function (err, data) {

            var jsonFileArr = [];
            jsonFileArr = JSON.parse(data); //Parse the data from JSON file
            var haveId = jsonFileArr.some(function (obj){ // Checks if the POST request have the same id as JSON file
                return obj.id == POST.id;
            })

            if (haveId) {  // if true
                var updateData = []; // Array with POST data
                updateData.push({
                    id: POST.id,
                    name: POST.name,
                    phone: POST.phone,
                })

                for(let Arr of jsonFileArr){
                  if (Arr.id == POST.id){
                    let currentIndex = jsonFileArr.indexOf(Arr);
                    jsonFileArr.splice(currentIndex,1,updateData) //removing the old object and adding the new one
                  }
                }

                var newUsers = JSON.stringify(jsonFileArr);
                fs.writeFile("file.json", '', "utf8",function(err,res){  //Making the file empty
                  if(!err){
                    fs.writeFile("file.json", newUsers, "utf8",function(err,res){ //Writing the whole object back
                      if(err)console.log(err);
                      console.info(res);
                    });
                  }else{
                    console.log(err);
                  }
                });

            }
        })
    }

I think this is better instead of using some, get the matching index and replace directly.

      var jsonFileArr = JSON.parse(data); //Parse the data from JSON file
      var foundId = jsonFileArr.findIndex(function (obj){ // Checks if the POST request have the same id as JSON file
          return obj.id == POST.id;
      });
      if (foundId >= 0) {
        jsonFileArr[foundId] = 
          {
                id: POST.id,
                name: POST.name,
                phone: POST.phone,
          }
      }

.... and then write back to file

Sign up to request clarification or add additional context in comments.

3 Comments

Wow thanks , it works ! But can u explain the ' for(var Arr of jsonFileArr) ' Loop. ( replaced let with var because my javascipt doesn't Support let ) I'm prety new.
for...of iterates over an iterable object, in this case an array. It runs the body of the loop for each item in the array, assigning the name Arr to the current item. Node 6+ should have support for let; 4 and 5 have partial support for it, although they don't have the proper block scope.
@UselessCode, Ye , i get an Block-scoped declaration error when i use 'let'. I think it's time to upgrade :) Thank you for your explanation

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.