我正在尝试更新 Express 应用程序中 JSON 文件中存储的项目。基本上,我正在读取 JSON 文件的内容,更新由 Id 获取的项目,并将更新后的项目写入文件。有问题吗? 它正在附加更新的项目,因此我得到了重复的项目。我看不出错误在哪里?
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 消失了? 谁能解释一下吗? - 谢谢
最佳答案
有两个问题:
您使用
push
将新项目插入列表中,这就是“重复”的原因config[item.id] = item;
不是有效的引用。你的配置不是这样的:["0071b034": { name: "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;
关于javascript - 查找并替换 Json 文件中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35246724/