[英]How to iterate over strings in request object?
In Express, I'm trying to scan the POST requests and create the array openingTimes
. 在Express中,我试图扫描POST请求并创建数组
openingTimes
。 And then create a MongoDB document , based on the inputs. 然后根据输入内容创建一个MongoDB文档。
Following code snippet works fine but how can I make a loop instead of defining n days? 遵循以下代码段可以正常工作,但是如何进行循环而不是定义n天?
`module.exports.myController = function (request, response) {
MongoDBModel.create({
name: req.body.name,
//I want to make a loop in here, so I dont have to define each day separately
openingTimes: [{
days: req.body.days1
, opening: req.body.opening1
, closing: req.body.closing1
, closed: req.body.closed1
}, {
days: req.body.days2
, opening: req.body.opening2
, closing: req.body.closing2
, closed: req.body.closed2
}]
// catching errors
}, function (err, location) {
if (err) {
sendJsonResponse(res, 400, err);
console.log("error is " + err);
}
else {
sendJsonResponse(res, 201, location);
}
});
};`
You could create the array beforehand (or inline with an IIFE that returns the array). 您可以预先创建数组(或与返回数组的IIFE内联)。
var numDays = 7;
var openingTimes = [];
for (var i = 1; i <= numDays; i++) {
openingTimes.push({
days: reg.body['days' + i],
opening: req.body['opening' + i],
closing: req.body['closing' + i],
closed: req.body['closed' + i]
});
}
MongoDBModel.create({
name: req.body.name,
openingTimes: openingTimes
}, etc);
Or with ES6, you could be creative and make an IIFE with a generator function. 或者使用ES6,您可以发挥创造力,并使用生成器功能创建IIFE。
const numDays = 7;
MongoDBModel.create({
name: req.body.name,
openingTimes: [...function*() {
for (let i = 1; i <= numDays; i++) {
yield {
days: reg.body['days' + i],
opening: req.body['opening' + i],
closing: req.body['closing' + i],
closed: req.body['closed' + i]
};
}
}()]
}, etc);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.