【问题标题】:How can I delete a key from my JSON if its empty如果它为空,我如何从我的 JSON 中删除一个密钥
【发布时间】:2019-08-13 20:21:00
【问题描述】:

如果键在其中没有值,我正在尝试从 js 对象中删除键。

我尝试使用 delete foundBrief.Contents.url 但没有奏效。我这样做是为了 alexa flash 简报技能。如果重定向 url 为空,则会引发错误,如果它为空,我必须删除该属性 url。

内容架构:

var contentSchema = new mongoose.Schema({
    _id : { type: String, default: uuid.v1},
     date: Date,
     titleText: String,
     mainText: String,
     Url: String,
     author:{
      id: {
       type: mongoose.Schema.Types.ObjectId,
       ref: "User"
      },
      username: String
     }
 },{
            versionKey: false
    });

使用路由在 url 上显示 json 对象:

router.get("/:id/abcd.json", function(req, res) {
  Brief.findById(req.params.id)
    .populate("contents")
    .exec(function(err, foundBrief) {
      if (err) {
        console.log(err);
      } else {
        console.log(foundBrief.contents);
       //[{"uid":"00a3b980-4ccc-11e9-ab44-dd6a45baec41","date":"2019-03-22T02:30:00.000Z","title":"title test","main":"content text","Url":""}]
        foundBrief.contents.forEach(function(element) {
            if(element.Url === ""){
                delete element.Url;
            }    
        });
      }
    });
});

有这个

[
  {
    uid: "00a3b980-4ccc-11e9-ab44-dd6a45baec41",
    date: "2019-03-22T02:30:00.000Z",
    title: "title test",
    main: "content text",
    Url: ""
  }
];

想要这个

[
  {
    uid: "00a3b980-4ccc-11e9-ab44-dd6a45baec41",
    date: "2019-03-22T02:30:00.000Z",
    title: "title test",
    main: "content text"
  }
];

【问题讨论】:

  • foundBrief.contents.forEach(...) 应该可以工作。你能创建一个最小的 sn-p 来重现这个问题吗?

标签: javascript node.js json express mongoose


【解决方案1】:
for(let obj of foundBrief.contents){
    Object.keys(obj).forEach(function(key){
      if(obj[key] === ''){
        delete obj[key];
      }
   })
}

【讨论】:

  • 不鼓励仅使用代码的答案。请添加一些关于如何解决问题的解释。 From Review
猜你喜欢
  • 2020-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多