我想遍历 JSON 对象树,但找不到任何库。看起来并不难,但感觉就像在重新发明轮子。
在 XML 中有很多教程展示了如何使用 DOM 遍历 XML 树 :(
最佳答案
如果你认为 jQuery 对于这样一个原始任务来说有点矫枉过正,你可以这样做:
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
//called with every property and its value
function process(key,value) {
console.log(key + " : "+value);
}
function traverse(o,func) {
for (var i in o) {
func.apply(this,[i,o[i]]);
if (o[i] !== null && typeof(o[i])=="object") {
//going one step down in the object tree!!
traverse(o[i],func);
}
}
}
//that's all... no magic, no bloated framework
traverse(o,process);
https://stackoverflow.com/questions/722668/