我有以下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迭代它?
当前回答
如果不容易,请告诉我:
var jsonObject = {
name: 'Amit Kumar',
Age: '27'
};
for (var prop in jsonObject) {
alert("Key:" + prop);
alert("Value:" + jsonObject[prop]);
}
其他回答
使用的…:
var mycars = [{name:'Susita'}, {name:'BMW'}]; 对于(MyCars的VaR Car) { document.write(car.name + “<br />”); }
结果:
Susita
BMW
对于嵌套对象,可以通过递归函数检索:
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对象一起使用不是很明智。
另一个在JSON文档中导航的解决方案是JSONiq(在Zorba引擎中实现),在那里你可以写这样的东西:
let $doc := [
{"id":"10", "class": "child-of-9"},
{"id":"11", "class": "child-of-10"}
]
for $entry in members($doc) (: binds $entry to each object in turn :)
return $entry.class (: gets the value associated with "class" :)
您可以在http://public.rumbledb.org:9090/public.html上运行它
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>