我有这个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
答案 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;