arrays - 使用 NODEJS 从 JSON 中删除元素

标签 arrays node.js json api

我有一个 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/

相关文章:

javascript - 如何使用 jQuery 在 JavaScript 数组中查找对象的索引

php - Array_filter 从数组中取消设置值

javascript - 这个对象是对象强制转换还是数组强制转换?

javascript - Sharepoint 2013 通过 REST API : Error 403 Forbidden when trying to create item

javascript - 返回具有特定属性的数组中的对象

javascript - "Emit"和 "On"套接字 IO,Node.js

node.js - 改进 Node.js 代码(sequelize、promise 和 Passport)

node.js - 无法解析模块 'child_process'

iphone - 在 iOS6 中使用 JSON

c# - Json.Net 从属性自定义序列化