如果密钥为空,如何从JSON中删除密钥

时间:2019-03-22 19:22:13

标签: javascript node.js json express mongoose

如果密钥内部没有值,我试图从js对象中删除密钥。

我尝试使用delete foundBrief.Contents.url删除,但没有用。我这样做是为了Alexa Flash简报技巧。如果重定向网址为空,则会引发错误。在这种情况下,如果该属性网址为空,则必须删除该属性网址。

ContentSchema:

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"
  }
];

1 个答案:

答案 0 :(得分:0)

for(let obj of foundBrief.contents){
    Object.keys(obj).forEach(function(key){
      if(obj[key] === ''){
        delete obj[key];
      }
   })
}