我有一个看起来像这样的JSON:
{
"success": false,
"error": {
"username": [
"The username has already been taken."
],
"email_address": [
"The email address has already been taken."
]
}
}
我想将所有消息存储在一个数组中。现在,我通过逐个检查手动完成。还有更好的方法吗?
答案 0 :(得分:1)
您可以使用Object.keys
方法返回带有error
键的数组。
然后,您可以使用Array
,map
,forEach
等任何reduce
方法对其进行迭代,以收集自己的消息。
const response = {
"success": false,
"error": {
"username": [
"The username has already been taken.",
"Another message"
],
"email_address": [
"The email address has already been taken."
]
}
};
const result = Object.keys(response.error)
.reduce((acc, key) => acc.concat(response.error[key]), []);
console.log(result);
答案 1 :(得分:0)
这是你如何获取数组中的所有消息
var a = {
"success": false,
"error": {
"username": [
"The username has already been taken."
],
"email_address": [
"The email address has already been taken."
]
}
}
var keys = Object.keys(a['error'])
var errors = a['error']
var c = [];
for(var i=0; i< keys.length; i++){
c.push(a['error'][keys[i]][0])
}
console.log(c)