[英]How to convert JSONObject to a JSONArray?
最近在Android APP中嘗試實現評論功能時遇到了這個問題。
user.js 中注釋的定義如下
comnents: [{
ownerID: {
type: String,
required: true,
},
commenterID: {
type: String,
required: true,
},
commenterName: String,
content: {
type: String,
require: true,
}
}],
我有一個這樣的要求:
{
"_id":"60d204d6efc6c70022b08dc4",
"comments":[
{
"ownerID":"60d204d6efc6c70022b08dc4",
"commenterID":"60d205afefc6c70022b08dc8",
"commenterName":"Bob",
"content":"Hello World!"
},
{
"ownerID":"60d204d6efc6c70022b08dc4",
"commenterID":"60d20892efc6c70022b08dd2",
"commenterName":"Alice",
"content":"Hello Earth!"
}
]
}
這是我的 API
router.post("/writecomment",jsonParser,
async(req,res,next)=>{
const errors=validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({erros:errors.array()});
}
User.findOneAndUpdate(
{ "_id": req.body._id},
{
$set: {
comments:req.body.comments
}
},
{overwrite:true},
function(err,resp){
if(err) throw err;
if(resp) {
return res.send({
msg:' change successfully'
});
}else{
return res.status(403).json({ success: false, message: 'Failed to change'});
}
}
)
}
)
如何將“評論”從請求轉換為評論數組? 或者有更好的方法來實現這個功能?
PS:我使用Mongoose + Express Framework 來開發。
const commentArray = [...req.body.comments]
會為你做這個:
[
{
"ownerID": "60d204d6efc6c70022b08dc4",
"commenterID": "60d205afefc6c70022b08dc8",
"commenterName": "Bob",
"content": "Hello World!"
},
{
"ownerID": "60d204d6efc6c70022b08dc4",
"commenterID": "60d20892efc6c70022b08dd2",
"commenterName": "Alice",
"content": "Hello Earth!"
}
]
基本上這里發生的事情是,我們正在迭代您得到的響應並將結果保存在一個數組中。 如果您想了解有關...
運算符的更多信息,請查看此鏈接: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.