使用JavaScript遍历JSON对象树的所有节点 [英] Traverse all the Nodes of a JSON Object Tree with JavaScript
本文介绍了使用JavaScript遍历JSON对象树的所有节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想遍历一个JSON对象树,但找不到任何库。这似乎并不困难,但感觉就像重新发明轮子一样。
I'd like to traverse a JSON object tree, but cannot find any library for that. It doesn't seem difficult but it feels like reinventing the wheel.
在XML中有很多教程展示了如何使用DOM遍历XML树:(
In XML there are so many tutorials showing how to traverse an XML tree with DOM :(
推荐答案
如果您认为jQuery对于这样一个原始任务有点矫枉过正,您可以这样做:
If you think jQuery is kind of overkill for such a primitive task, you could do something like that:
//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);
这篇关于使用JavaScript遍历JSON对象树的所有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文