我有以下的JSON结构:
[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]
我该如何使用JavaScript迭代它?
[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]
我该如何使用JavaScript迭代它?
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);
}
}
for key in obj
循环中检查 obj.hasOwnProperty(key)
--- 否则,如果有人扩展了原型,你可能会发现其他键正在进入 obj
中,而你并不想要它们。 - Funka摘自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));
});
使用 for...of:
var mycars = [{name:'Susita'}, {name:'BMW'}];
for (var car of mycars)
{
document.write(car.name + "<br />");
}
结果:
Susita
BMW
如果不容易,请让我知道:
var jsonObject = {
name: 'Amit Kumar',
Age: '27'
};
for (var prop in jsonObject) {
alert("Key:" + prop);
alert("Value:" + jsonObject[prop]);
}
如果这是你的dataArray
:
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;
});
从http://www.w3schools.com复制并粘贴,没有必要增加JQuery的开销。
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x];
}
结果:John Doe 25
mootools 示例:
var ret = JSON.decode(jsonstr);
ret.each(function(item){
alert(item.id+'_'+item.classd);
});
你可以使用像objx这样的迷你库 - http://objx.googlecode.com/
你可以编写类似于以下代码:
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()
有更多的“插件”可用于处理这样的数据,参见http://code.google.com/p/objx-plugins/wiki/PluginLibrary
使用递归函数可以检索嵌套对象:
function inside(events)
{
for (i in events) {
if (typeof events[i] === 'object')
inside(events[i]);
else
alert(events[i]);
}
}
inside(events);
其中events是JSON对象。
当使用jQuery时,Marquis Wang的方法可能是最好的答案。
在纯JavaScript中也有类似的解决方案,可以使用JavaScript的forEach方法。 forEach 接受一个函数作为参数,该函数将针对数组中的每个项目进行调用,并将该项目作为参数。
简单易懂:
var results = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"} ];
results.forEach(function(item) {
console.log(item);
});
results.forEach((item) => console.log(item));
- quasar