如何使用javascript迭代JSON数组?

时间:2018-04-05 03:58:40

标签: javascript jquery json

我有这个JSON数据:

var obj = {
        "result": [
            [
                {
                    "PARAM 1": [
                        {
                            "field": "firstName",
                            "message": "Parameter is required",
                            "moreInfo": "https://google.com",
                            "responseCode": "-1015"
                        },
                        {
                            "field": "lastName",
                            "message": "Parameter is required",
                            "moreInfo": "https://google.com",
                            "responseCode": "-1015"
                        }
                    ]
                }
            ],
            [
                {
                    "PARAM 2": [
                        {
                            "field": "ZipCode",
                            "message": "Invalid Code",
                            "moreInfo": "https://google.com",
                            "responseCode": "-1020"
                        }
                    ]
                }
            ]
        ]
    }

我希望得到结果基于" responseCode" 我希望在下面显示以下结果。

示例输出:

姓名详情:< - PARAM 1

  • 参数是必需的
  • 手机号码无效

ADDRESS DETAILS:< - PARAM 2

  • 无效的ZipCode
  • 无效字符

1 个答案:

答案 0 :(得分:0)

虽然以下代码有效,但您可以考虑更改正在创建的对象的格式。这很容易遇到很多问题。



var obj = {
    "result": [
        [
            {
                "PARAM 1": [
                    {
                        "field": "firstName",
                        "message": "Parameter is required",
                        "moreInfo": "https://google.com",
                        "responseCode": "-1015"
                    },
                    {
                        "field": "lastName",
                        "message": "Parameter is required",
                        "moreInfo": "https://google.com",
                        "responseCode": "-1015"
                    }
                ]
            }
        ],
        [
            {
                "PARAM 2": [
                    {
                        "field": "ZipCode",
                        "message": "Invalid Code",
                        "moreInfo": "https://google.com",
                        "responseCode": "-1020"
                    }
                ]
            }
        ]
    ]
};
var headingArray = ['NAME DETAILS', 'ADDRESS DETAILS'];
obj.result.forEach((elem, index) => {
    var key = "PARAM "+(index+1);
    $("#value").append($("<p>"+headingArray[index]+": <-- "+key+"</p>"));
    elem[0][key].forEach(subElement => {
       $("#value").append($("<li>"+subElement.message+"</li>"));
    })
    
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="value"></div>
&#13;
&#13;
&#13;