如何用NodeJS的新对象替换旧的JSON对象

2022-04-12 00:00:00 json node.js javascript crud

如何将使用NodeJS的旧JSON对象替换为新的更新对象?

现在,当我更新json文件时,它会将新数据与旧数据一起保存。

JSON:

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

以下是我的代码:

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

我可能应该使用delete object,但我如何指定应该删除哪个对象?

因此,当我更新ID为%1的数据时,它会删除旧的ID/姓名/电话并写入新数据。


解决方案

我根据您的问题假设您在一个文件中有多个对象。因此,解决此问题的最简单方法是

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

            }
        })
    }

我认为这比使用某些索引更好,获取匹配的索引并直接替换。

      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,
          }
      }

...然后写回文件

相关文章