使用 JavaScript 遍历 JSON 对象树的所有节点 [英] Traverse all the Nodes of a JSON Object Tree with JavaScript

查看:34
本文介绍了使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆