【问题标题】:How to replace old json object with a new one with NodeJS如何使用 NodeJS 用新对象替换旧的 json 对象
【发布时间】:2016-12-07 13:08:55
【问题描述】:

如何使用 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/姓名/电话并写入新数据。

【问题讨论】:

    标签: javascript json node.js crud


    【解决方案1】:

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

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

    ....然后写回文件

    【讨论】:

    • 哇,谢谢,它有效!但是你能解释一下'for(var Arr of jsonFileArr)'循环吗? (用 var 替换 let 因为我的 javascipt 不支持 let )我很新。
    • for...of 迭代一个可迭代对象,在本例中是一个数组。它为数组中的每个项目运行循环体,将名称 Arr 分配给当前项目。 Node 6+ 应该支持let; 4 和 5 有 partial support ,尽管它们没有正确的块范围。
    • @UselessCode,是的,当我使用“let”时,我得到一个块范围的声明错误。我想是时候升级了:)谢谢你的解释
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多