【问题标题】:Find And Replace Items In A Json file查找和替换 Json 文件中的项目
【发布时间】:2016-12-17 09:43:47
【问题描述】:

我正在尝试在 Express 应用中更新存储在 JSON 文件中的项目。基本上我正在读取 JSON 文件的内容,更新 Id 获取的项目并将更新后的 item.Problem 写入文件? 它正在附加更新的项目,所以我得到了重复。看不到哪里出错了?

posts.json:

[
    {
        "name": "first name",
        "description": "test first description",
        "slug": "first-name",
        "id": "2f065d59"
    },
   {
        "name": "second name",
        "description": "test second description",
        "slug": "second-name",
        "id": "0071b034"
    }
]

create-update-delete.js:

var express = require('express');
var Creatordb = require('./database/posts.json');
var fs = require('fs');
var uuid = require('node-uuid');
var _ = require('lodash');

 //Create The Item           
var add = function (item) {
  var id = uuid.v4();
  item.id = id;
  Creatordb[item.id] = item;
  var outputFilename = './database/posts.json'; 

  function appendObject(obj){
    var configFile = fs.readFileSync(outputFilename);          
    var config = JSON.parse(configFile); 

    config.push(obj);           

    var configJSON = JSON.stringify(config, null, 4);

    fs.writeFileSync(outputFilename, configJSON);

  }
  appendObject(item);
};

//Get The Item by Id
var getById = function (id) {
  for(var i=0;i<Creatordb.length;i++) {
    var id = Creatordb[i].id;
  }
  return id;
};

//Update The Item 
var update = function (item) {        
  var outputFilename = './database/posts.json'; 
  var configFile = fs.readFileSync(outputFilename);

  var config = JSON.parse(configFile); 


  //using lodash??
 var index = _.indexOf(config, _.find(config, item));

 config.splice(index, 1, item);

  var configJSON = JSON.stringify(config, null, 4);

  fs.writeFileSync(outputFilename, configJSON);

};

如果我更新一个项目,posts.json 将如下所示:

 [
        {
            "name": "first name",
            "description": "test first description",
            "slug": "first-name",
            "id": "2f065d59"
        },

        {
            "name": "second name edited",
            "description": "test second description edited",
            "slug": "second-name-edited",
            //this id disappeared "id": "0071b034"//
        }
    ]

现在使用 lodash 更新项目中的 ID 消失了吗? 谁能解释一下? - 谢谢

【问题讨论】:

    标签: javascript arrays json node.js express


    【解决方案1】:

    有两个问题:

    1. 您使用push 将新项目插入列表中,这是“重复”的原因

    2. config[item.id] = item; 不是有效的参考。你的配置不是这样的:

      [“0071b034”:{名称:“Foo”}]

    所以配置中的键是 0,1,2 而不是item.id

    我建议使用lodash。有很多有用的功能,但如果你坚持这个实现,就用这个:

    function findIndex(collection, id) {
      for(var i=0; i<collection.length; i++) {
        if (collection[i].id === id) {
          return i;
        }
      }
    }
    
    // In your update function
    var index = findIndex(config, item.id);
    config[index] = item;
    

    【讨论】:

    • 话虽如此,如果他的数据结构基于项目ID而不是索引,那么看起来他正在做的事情会更容易。
    • 感谢您的回答 Festo 但是如何在不推送的情况下将更新的项目添加到数组中??
    • 更新索引 config[index] = item index 应该是元素的索引。你可以用for循环扫描,或者在拿到之前保存。
    • 我尝试像这样循环 link 但没有用。也许我会开始搜索以实现像 mongodb 这样的外部数据库
    • 感谢 Festo 我开始使用 lodash 但现在我的 id 消失了。在更新功能上我使用 lodash 如下:var index = _.indexOf(config, _.find(config, item)); config.splice(index, 1, item); 然后 json.stringify(config,null,4) 在 posts.json 上更新的 id项目不见了。??
    【解决方案2】:

    我不明白,你为什么在update 中使用splice 函数?在 JavaScript 中,当您处理对象或数组时,您使用的是它们的引用,而不是副本。所以,你可以用这个替换splice

    var obj = _.find(config, ['id', item.id]);
    _.assign(obj, item);
    

    在这种情况下,您不必关心项目是否具有所有必需的字段,因为assign 方法将仅更新指定的那些字段。

    同时,如果您 100% 确定新项目将始终指定所有字段,那么 Festo 的解决方案会更好,因为它只是在新项目上替换旧项目的引用,这要快得多。

    var config = [
        {
            "name": "first name",
            "description": "test first description",
            "slug": "first-name",
            "id": "2f065d59"
        },
       {
            "name": "second name",
            "description": "test second description",
            "slug": "second-name",
            "id": "0071b034"
        }
    ];
    
    function update(item) {
      // Your read file logic.
      
      var obj = _.find(config, ['id', item.id]);
      _.assign(obj, item);
      
      // Your write file logic.
    }
    
    console.log('config befor update:', config);
    update({  
      "name": "third name",
      "id": "0071b034"
    });
    console.log('config after update:', config);
    &lt;script src="https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      • 2011-07-18
      相关资源
      最近更新 更多