我有以下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 mycars = [{name:'Susita'}, {name:'BMW'}]; 对于(MyCars的VaR Car) { document.write(car.name + “<br />”); }
结果:
Susita
BMW
其他回答
取自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));
});
你可以使用像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);
其中as events是json object。
使用的…:
var mycars = [{name:'Susita'}, {name:'BMW'}]; 对于(MyCars的VaR Car) { document.write(car.name + “<br />”); }
结果:
Susita
BMW
mootools的例子:
var ret = JSON.decode(jsonstr);
ret.each(function(item){
alert(item.id+'_'+item.classd);
});