我有一个 json 文件,我正在尝试使用以下代码删除一个元素。
exports.delete = function(req, res) {
var deletearticle = articles[req.params.id];
delete articles[req.params.id];
fs.writeFile('server/articles.json',JSON.stringify(articles, null, 4),finished);
function finished(err){
console.log("--->After deletion, article list:\n" + JSON.stringify(articles, null, 4) );
}
res.end(JSON.stringify(deletearticle, null, 4));
};
删除元素后,我的 json 文件将如下所示:
[
{
"header": "Jack",
"body": "Davis",
"date": "",
"id": 0
},
null,
{
"header": "dfd",
"body": "dgfgfgfgfdgfg",
"date": "2018-11-24T16:33:48.842Z",
"id": 2
}]
我在客户端收到错误:
{articles ? articles.map(({ id, header ,body}) => (
<div key={id} timeout={500} className="fade">
<div className="article">
<h2 className="article_title">{header}</h2>
因为我的 JSON 元素之一为 null,所以它表示无法从 null 读取 id。是否有更好的方法从我的 json 文件中删除此元素?或者我可以检查客户端中的 srtile 是否不为空。
最佳答案
只需过滤你的对象,假设这里 a 是你的 JSON 数组,你必须过滤所有不包含 null 的对象
a = a.filter(function(obj){ if(obj != null) return obj })
现在打印a,它将过滤掉除空对象之外的所有对象
关于arrays - 使用 NODEJS 从 JSON 中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53475098/