javascript - 遍历嵌套对象/数组

标签 javascript loops yui3

我正在尝试遍历一个可以具有多级数组的对象。

例如。

我开始于:

var htmlString = {
    "div": [{
        "attributes": {
            "class": "myDivClass"
        },
        "p": [{
            "attributes": {
                "class": "myPClass"
            }
        }]
    }]
};

现在让我们添加一些东西:

var htmlString = {
    "div": [{
        "attributes": {
            "class": "myDivClass"
        },
        "p": [{
            "attributes": {
                "class": "myPClass"
            },
            "span": [{
                "attributes": {
                    "class": "mySpanClass"
                }
            }]
        }]
    }]
};

我正在处理的代码将具有与以下相同的形状:

var childNode = document.createElement("myChildElement");
for (key in value) {
    if (value.hasOwnProperty(key)) {
        if (key == "attributes") {
            childNode.setAttributes(myAttributes); // loop through attributes on the element
        }
        else {
            //the same code ad infinitum
            var childChildNode = document.createElement("myChildChildElement");
            // etc etc....
        }
    }
}
parentNode.appendChild(childNode);

每个额外元素的规则都是相同的,所以我应该能够对这两段代码以相同的方式循环这个数据结构,我只是不确定如何,尽管我敢打赌while() 在某处循环。谁能告诉我?

附言原生 javascript,拜托,不要 jQuery! (不过,如果您有 YUI3 答案,我会非常感兴趣)。

最佳答案

var createTree = function (node, data) {
    for (var key in data) {
        if (data.hasOwnProperty(key)) {
            if (key == "attributes") {
                node.setAttributes(myAttributes); // loop through attributes on the element
            }
            else {
                for (var i = 0; i < data[key].length; ++i) {
                    var childNode = document.createElement(key);
                    createTree(childNode, data[key][i]);
                    node.appendChild(childNode);
                }
            }
        }
    }
}

createTree(parentNode, htmlString);

关于javascript - 遍历嵌套对象/数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11764142/

相关文章:

javascript - 如何使用一个依赖于另一个的 2 个 XMLHttpRequest?

c# - 如何在实际将其发送到服务器之前显示正在上传的图像的预览

javascript 对象 HTMLIFrameElement 错误

PHP 循环巨大的文本文件非常慢,你能改进吗?

javascript - 职位固定问题

css - 如何有选择地为 YUI 模块加载/使用 CSS?

javascript - 在 YUI3 的自定义模块上定义和触发自定义事件

javascript - 从 ngRoute 迁移到 ui.router

c# - 在 C# 中相当于 Ruby "redo"

c++ - Visual C++ - 运行时检查失败 #3 - 变量未初始化