我正在使用快速验证器来验证json正文。
router.post('/login', [
body('mobno')
.exists().withMessage('Required')
.isLength({ min: 10, max: 12 }).withMessage('10-12 characters')
.isNumeric().withMessage('Numeric'),
body('password')
.not().isEmpty().withMessage('Password is required'),
], async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.json({ errors: errors.array(), success: false, msg: 'Check Parameters' });
}
// do stuff and respond
});
{
"errors": [
{
"value": "998716***658()",
"msg": "10-12 characters",
"param": "mobno",
"location": "body"
},
{
"value": "998716***658()",
"msg": "Numeric",
"param": "mobno",
"location": "body"
}
],
"success": false,
"msg": "Check Parameters"
}
在前端,我正在使用Vuetify,因此我需要将共振设为一种易于被前端使用的格式。
{
"errors": {
"mobno": [
"10-12 characters",
"Numeric"
]
},
"success": false,
"msg": "Check Parameters"
}
errors
。 答案 0 :(得分:1)
您可以使用lodash链按param
将错误分组,然后将每个组中的项目映射到msg
属性。然后,您可以使用对象传播将errors
对象与先前的结果组合在一起。
const data = {"errors":[{"value":"998716***658()","msg":"10-12 characters","param":"mobno","location":"body"},{"value":"998716***658()","msg":"Numeric","param":"mobno","location":"body"}],"success":false,"msg":"Check Parameters"}
const errors = _(data.errors)
.groupBy('param')
.mapValues(group => _.map(group, 'msg'))
.value()
const result = {
...data,
errors
}
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.14/lodash.js"></script>
以及使用lodash / fp和_.flow()
的管道方法:
const { flow, groupBy, mapValues, map } = _
const transform = flow(
groupBy('param'),
mapValues(map('msg'))
)
const data = {"errors":[{"value":"998716***658()","msg":"10-12 characters","param":"mobno","location":"body"},{"value":"998716***658()","msg":"Numeric","param":"mobno","location":"body"}],"success":false,"msg":"Check Parameters"}
const result = {
...data,
errors: transform(data.errors)
}
console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>