使用NODEJS从JSON删除元素

时间:2018-11-26 05:16:30

标签: 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文件中删除此元素?或者我可以在客户端检查srticle是否不为空。

4 个答案:

答案 0 :(得分:2)

只需过滤您的对象,假设这里是您的JSON数组,那么您必须过滤所有不包含null的对象

a = a.filter(function(obj){ if(obj != null) return obj })

现在打印一个,它将滤除除空对象之外的所有对象

答案 1 :(得分:1)

您可以像这样删除元素而不保留null ...

 array.splice(index, 1);

或者,您可以通过执行以下操作删除空元素...

var array = [
    {
        "header": "Jack",
        "body": "Davis",
        "date": "",
        "id": 0
    },
    null,
    {
        "header": "dfd",
        "body": "dgfgfgfgfdgfg",
        "date": "2018-11-24T16:33:48.842Z",
        "id": 2
    }];

// filter array

var filtered = array.filter(function (el) {
  return el != null;
});

答案 2 :(得分:1)

    var a = [
        {
            "header": "Jack",
            "body": "Davis",
            "date": "",
            "id": 0
        },
        null,
        {
            "header": "dfd",
            "body": "dgfgfgfgfdgfg",
            "date": "2018-11-24T16:33:48.842Z",
            "id": 2
        }];

   //using es6 array.filter to filter null or undefined or empty object

    var filtered = array.filter((x)=>{ 
      for (var key in filter) {
        if (x[key] === undefined || x[key] !== null || x[key]!=='')
          return false;
     }
     return true;
   });

答案 3 :(得分:1)

您可以使用array.splice从数组中删除对象,因为有了对象的ID,首先需要找到要删除的对象的索引,然后可以使用拼接轻松地将其删除。 / p>

供您参考,avoid using delete

var sampleArray= [{
    "header": "Jack",
    "body": "Davis",
    "date": "",
    "id": 5
  },
  {
    "header": "Jack",
    "body": "Davis",
    "date": "",
    "id": 6
  },
  
  {
    "header": "dfd",
    "body": "dgfgfgfgfdgfg",
    "date": "2018-11-24T16:33:48.842Z",
    "id": 7
  }
];

var id = 5;

var index = sampleArray.findIndex(a=> a.id === id);
if (index > -1) {
  sampleArray.splice(index, 1);
}

console.log(sampleArray);