如何使用NodeJS替換舊的json對象

[英]How to replace old json object with a new one with NodeJS


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

如何使用NodeJS用新的更新對象替換舊的json對象?

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

現在,當我更新json文件時,它將使用舊數據保存新數據。

JSON :

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.

所以當我用id 1更新數據時,它會刪除舊的id / Name / phone並寫入新數據。

1 个解决方案

#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

....然后寫回文件


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/08/02/72fb675437854d3066dd564cd22ef7f0.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com