[英]How can I delete a key from my JSON if its empty
I am trying to delete the key from js object if key doesn't have value inside of it.如果密钥内部没有值,我试图从 js 对象中删除密钥。
I have tried using delete foundBrief.Contents.url but not worked.我曾尝试使用 delete foundBrief.Contents.url 但没有奏效。 I am doing this for alexa flash briefing skill.
我这样做是为了alexa flash简报技巧。 It throws error if the redirection url is blank I have to remove that attribute url in that case if its empty.
如果重定向 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
});
To display json object on the url using routes:要使用路由在 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;
}
});
}
});
});
Have this有这个
[
{
uid: "00a3b980-4ccc-11e9-ab44-dd6a45baec41",
date: "2019-03-22T02:30:00.000Z",
title: "title test",
main: "content text",
Url: ""
}
];
want this想要这个
[
{
uid: "00a3b980-4ccc-11e9-ab44-dd6a45baec41",
date: "2019-03-22T02:30:00.000Z",
title: "title test",
main: "content text"
}
];
for(let obj of foundBrief.contents){
Object.keys(obj).forEach(function(key){
if(obj[key] === ''){
delete obj[key];
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.