本文翻譯自:How do I iterate over a JSON structure? [duplicate]
This question already has an answer here: 這個問題已經在這裏有了答案:
- For-each over an array in JavaScript? 在JavaScript中逐個遍歷數組? 33 answers 33個答案
I have the following JSON structure: 我具有以下JSON結構:
[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]
How do I iterate over it using JavaScript? 如何使用JavaScript進行迭代?
#1樓
參考:https://stackoom.com/question/4WT0/如何遍歷JSON結構-重複
#2樓
Taken from jQuery docs : 取自jQuery docs :
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));
});
#3樓
mootools example: mootools示例:
var ret = JSON.decode(jsonstr);
ret.each(function(item){
alert(item.id+'_'+item.classd);
});
#4樓
You can use a mini library like objx - http://objx.googlecode.com/ 您可以使用像物objx一個迷你圖書館- http://objx.googlecode.com/
You can write code like this: 您可以編寫如下代碼:
var data = [ {"id":"10", "class": "child-of-9"},
{"id":"11", "class": "child-of-10"}];
// alert all IDs
objx(data).each(function(item) { alert(item.id) });
// get all IDs into a new array
var ids = objx(data).collect("id").obj();
// group by class
var grouped = objx(data).group(function(item){ return item.class; }).obj()
There are more 'plugins' available to let you handle data like this, see http://code.google.com/p/objx-plugins/wiki/PluginLibrary 還有更多“插件”可用於處理此類數據,請參閱http://code.google.com/p/objx-plugins/wiki/PluginLibrary
#5樓
var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"}];
for (var i = 0; i < arr.length; i++){
var obj = arr[i];
for (var key in obj){
var attrName = key;
var attrValue = obj[key];
}
}
var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "class": "child-of-10"}]; for (var i = 0; i < arr.length; i++){ document.write("<br><br>array index: " + i); var obj = arr[i]; for (var key in obj){ var value = obj[key]; document.write("<br> - " + key + ": " + value); } }
note: the for-in method is cool for simple objects. 注意:for-in方法對於簡單對象很酷。 Not very smart to use with DOM object. 與DOM對象配合使用不是很聰明。
#6樓
Another solution to navigate through JSON documents is JSONiq (implemented in the Zorba engine), where you can write something like: 導航JSON文檔的另一種解決方案是JSONiq (在Zorba引擎中實現),您可以在其中編寫如下內容:
jsoniq version "1.0";
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" :)
You can run it on http://try.zorba.io/ 您可以在http://try.zorba.io/上運行它