在Angular应用程序中,我从服务器获得HTTP响应作为JSON对象,但有一些错误。我想将它们全部加入到一个字符串中,并将它们显示为用户的消息。
目前,我已经这样做了:
if ( "errors" in emsg.error ) {
let msg = emsg.error.map(o => o.name).join(', ');
}
但是,我需要为每个不同的键名称返回的情况编写它。我的回答的一个例子就是这个:
{
"error":{
"message":"422 Unprocessable Entity",
"errors":{
"id":[
"The id has already been taken."
],
"name":[
"The name has already been taken."
]
},
"status_code":422
}
}
因此,我的响应可以包含动态对象名称,并且每个名称都可能有多个错误。有没有办法将上面的内容转换为处理相同格式的所有响应的通用代码?
答案 0 :(得分:2)
var emsg = {
"error":{
"message":"422 Unprocessable Entity",
"errors":{
"id":[
"The id has already been taken."
],
"name":[
"The name has already been taken."
]
},
"status_code":422
}
}, array = [];
// push all error values into array
for (var key in emsg.error.errors) {
Array.prototype.push.apply(array, emsg.error.errors[key]);
}
console.log(array.join(', '));
如果您可以使用lodash
,则可以使用flatMap
更优雅地完成此操作,
_.flatMap(emsg.error.errors).join(', ');
答案 1 :(得分:1)
获取对象键并迭代键数组。如果密钥存在,则加入值
var emsg = {
"error":{
"message":"422 Unprocessable Entity",
"errors":{
"id":[
"The id has already been taken."
],
"name":[
"The name has already been taken."
]
},
"status_code":422
}
}
var keys = Object.keys(emsg.error.errors);
let msg = keys.map(o =>emsg.error.errors[o] ).join(', ');
console.log(msg)