我有以下JSON结构:
[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]
我如何使用JavaScript迭代它?
我有以下JSON结构:
[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]
我如何使用JavaScript迭代它?
当前回答
对于嵌套对象,可以通过递归函数检索:
function inside(events)
{
for (i in events) {
if (typeof events[i] === 'object')
inside(events[i]);
else
alert(events[i]);
}
}
inside(events);
其中as events是json object。
其他回答
var arr = [{" id ":“10”,“类”:" child-of-9 "}, {" id ":“11”,“类”:“child-of-10”}); For (var I = 0;I < arrr .length;我+ +){ 文档。写("<br><br>数组索引:" + i); Var obj = arr[i]; For (var key in obj){ Var值= obj[key]; 文档。Write ("<br> - " + key + ": " + value "); } }
注意:for-in方法对于简单对象很酷。与DOM对象一起使用不是很明智。
var jsonString = `{ "schema": { "title": "User Feedback", "description": "so", "type": "object", "properties": { "name": { "type": "string" } } }, "options": { "form": { "attributes": {}, "buttons": { "submit": { "title": "It", "click": "function(){alert('hello');}" } } } } }`; var jsonData = JSON.parse(jsonString); function Iterate(data) { jQuery.each(data, function (index, value) { if (typeof value == 'object') { alert("Object " + index); Iterate(value); } else { alert(index + " : " + value); } }); } Iterate(jsonData); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
取自jQuery文档:
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
如果这是你的数据数组:
var dataArray = [{"id":28,"class":"Sweden"}, {"id":56,"class":"USA"}, {"id":89,"class":"England"}];
然后:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var CLASS = this.class;
});
对于嵌套对象,可以通过递归函数检索:
function inside(events)
{
for (i in events) {
if (typeof events[i] === 'object')
inside(events[i]);
else
alert(events[i]);
}
}
inside(events);
其中as events是json object。