如果它是空的,我如何从我的JSON中删除密钥

问题描述 投票:-3回答:1

我试图从js对象中删除密钥,如果key里面没有值。

我尝试过使用delete foundBrief.Contents.url但没有用。我正在为alexa flash简报技巧这样做。如果重定向url为空,则抛出错误我必须删除该属性url,如果它为空。

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"
  }
];
javascript node.js json express mongoose
1个回答
0
投票
for(let obj of foundBrief.contents){
    Object.keys(obj).forEach(function(key){
      if(obj[key] === ''){
        delete obj[key];
      }
   })
}
© www.soinside.com 2019 - 2024. All rights reserved.