我通过AJAX获得此JSON数组:
{
"success": 1,
"message": {
"ar": {
"total": 747.4851,
"list": [{
"total_statements": 1,
"total_due": 747.4851,
"name": "Paul McBilling",
"connection_id": 154
}]
},
"ap": {
"total": 0,
"list": []
},
"graphs": {
"graph": {
"2016-01": 13,
"2016-02": 0,
"2016-03": 0,
"2016-04": 747.4851,
"2016-05": 0,
"2016-06": 0,
"2016-07": 0,
"2016-08": 0,
"2016-09": 0,
"2016-10": 0,
"2016-11": 0,
"2016-12": 0
}
},
"cached": 1
}
}
我想得到的结果将类似于以下内容(在控制台中):
2016-01: 13
2016-02: 0
...
我正在尝试记录内部“图形”数组的每个键和值对。
我已经试过了:
$(data.message.graphs.graph).each(function(key, value){
console.log(key +' and '+ value);
});
但是返回的结果只有一次:
0 and [object Object]
您需要使用jQuery.each()
迭代对象
var data = {
"success": 1,
"message": {
"ar": {
"total": 747.4851,
"list": [{
"total_statements": 1,
"total_due": 747.4851,
"name": "Paul McBilling",
"connection_id": 154
}]
},
"ap": {
"total": 0,
"list": []
},
"graphs": {
"graph": {
"2016-01": 13,
"2016-02": 0,
"2016-03": 0,
"2016-04": 747.4851,
"2016-05": 0,
"2016-06": 0,
"2016-07": 0,
"2016-08": 0,
"2016-09": 0,
"2016-10": 0,
"2016-11": 0,
"2016-12": 0
}
},
"cached": 1
}
}
$.each(data.message.graphs.graph,function(key, value) {
console.log(key + ' and ' + value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
或者在纯JavaScript中,使用Object.keys()
获取键数组并对其forEach()
进行迭代。
var data = {
"success": 1,
"message": {
"ar": {
"total": 747.4851,
"list": [{
"total_statements": 1,
"total_due": 747.4851,
"name": "Paul McBilling",
"connection_id": 154
}]
},
"ap": {
"total": 0,
"list": []
},
"graphs": {
"graph": {
"2016-01": 13,
"2016-02": 0,
"2016-03": 0,
"2016-04": 747.4851,
"2016-05": 0,
"2016-06": 0,
"2016-07": 0,
"2016-08": 0,
"2016-09": 0,
"2016-10": 0,
"2016-11": 0,
"2016-12": 0
}
},
"cached": 1
}
}
Object.keys(data.message.graphs.graph).forEach(function(k) {
console.log(k + ' and ' + data.message.graphs.graph[k]);
});
甚至可以使用for...in
循环
var data = {
"success": 1,
"message": {
"ar": {
"total": 747.4851,
"list": [{
"total_statements": 1,
"total_due": 747.4851,
"name": "Paul McBilling",
"connection_id": 154
}]
},
"ap": {
"total": 0,
"list": []
},
"graphs": {
"graph": {
"2016-01": 13,
"2016-02": 0,
"2016-03": 0,
"2016-04": 747.4851,
"2016-05": 0,
"2016-06": 0,
"2016-07": 0,
"2016-08": 0,
"2016-09": 0,
"2016-10": 0,
"2016-11": 0,
"2016-12": 0
}
},
"cached": 1
}
}
for (var k in data.message.graphs.graph) {
if (data.message.graphs.graph.hasOwnProperty(k)) {
console.log(k + ' and ' + data.message.graphs.graph[k]);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句