如何使用数组循环json并获取所有值?

时间:2018-02-16 13:00:11

标签: javascript

我有一个看起来像这样的JSON:

{
"success": false,
"error": {
    "username": [
        "The username has already been taken."
    ],
    "email_address": [
        "The email address has already been taken."
    ]
}
}

我想将所有消息存储在一个数组中。现在,我通过逐个检查手动完成。还有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

您可以使用Object.keys方法返回带有error键的数组。 然后,您可以使用ArraymapforEach等任何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)