遍历复杂的嵌套json数组javascript

时间:2018-07-09 21:06:03

标签: javascript arrays json loops

nested json structure

Json结构:

{
"id": "30080",
        "dataelements": {
    "Name": "abc",
        },
        "children": [
            {
                "id": "33024",
                "dataelements": {
                    "Name": "a",
                    },
                "children": [
                    {
                        "id": "33024",
                        "dataelements": {
                            "Name": "b"

                            },
                        "children": [
                            {
                                "id": "33024",
                                "dataelements": {
                                    "Name": "z"
                                    },
                                "children": []
                            }
                        ]
                    }
                ]
            },
            {
                "id": "4800",
                "dataelements": {
                    "Name": "d"
                    },
                "children": [
                    {
                        "id": "4800",
                        "dataelements": {

.........................

我有如图所示的嵌套json数据。对于每个子对象,我创建一个节点模型。子对象可以在其中包含其他子对象。

 if (ele == "dataelements")
{
    var categoryNode = new NodeModel(
    {
        label: row.dataelements.Name,
        icons: [{ iconName: 'product'}],
        grid: row[ele] 
    });
}

if(ele == "children")
{
    var subCategoryNode;
    var subCategoryIndex = 1;
    for (var i = 0, len = row.children.length; i<len; i++) 
    {
        subCategoryNode = new NodeModel(
        {
            label: row.children[i].dataelements.Name,
            icons: [{
            iconName: '3dpart' }],
            grid: row.children[i].dataelements                             
        });

        categoryNode.addChild(subCategoryNode);
    }
}

此代码仅处理一级子节点。 当我不知道到底嵌套了多少个子级别时,该如何检查内部的子级别?

1 个答案:

答案 0 :(得分:0)

快速了解递归函数和需要注意的问题

  • 递归函数非常适合嵌套数据
  • 他们会在每次输入迭代之前调用自己,直到遇到基本情况为止
  • 起初缠头可能很棘手
  • 如果递归函数使用不当或输入大小过大,则会达到调用堆栈限制
  • 查找递归调用中使用的变量,使用 let 关键字告诉javascript将变量设置为当前作用域

解决方案

让我们假设您的JSON已通过验证,这就是下面示例中的结构。 如果我想遍历JSON中的所有元素,我想使用一个递归调用使它整洁,调试简单,易于构建。

下面是一个示例,该示例遍历给定的示例JSON以打印出分解视图。

如何使用以下代码

  • 复制 recursiveSearch 函数
  • 调用 recursiveSearch 函数,并传入JSON
  • 根据您的需要进行修改,我给了您一些基础

CODE

    var someJson = {"id": "30080","dataelements": {"Name": "abc"},"children": [{"id": "33024","dataelements": {"Name": "a"},"children": [{"id": "33024","dataelements": {"Name": "b"},"children": [{"id": "33024","dataelements": {"Name": "z"},"children": []}]}]}, {"id": "4800","dataelements": {"Name": "d"},"children": []}]};

    //we set level to 0 (optional variable) this means we can omit it in the inital call for neat code
    function recursiveScan(json, level=0)
    {
        //we store all of the output in a log and keep a track of the level to determine indenting
        var log = "";
        var indent = "";

        //based on the current level of the recursion, we indent the text to make it readable
        for (let i=0; i<level; i++)
        {
            indent += "&emsp;&emsp;";
        }

        //avoid any bad json or invalid data by checking if the name and id is null
        if(json.dataelements.Name != null && json.id != null)
        {
            //we know there is a valid element, write the name and id
            log += indent + "ID: " + json.id + "<br>";
            log += indent + "Name: " + json.dataelements.Name + "<br>";

            //if there is any children
            if(json.children.length > 0)
            {
                //just for neatness, lets draw the paranthesis
                log += indent + "{" + "<br>";

                //increase the level
                level++;

                //for each child, recursively call this function to get the next level of children if available
                for(let t=0; t<json.children.length; t++)
                {
                    log += recursiveScan(json.children[t], level);
                }

                //we are dropping our recursion level now, getting ready to return;
                level--;
                //close the paranthesis for neatness
                log += indent + "}" + "<br>";
            }
        }

        //return the final log
        return log;
    }

    //now lets test the code
    document.write(recursiveScan(someJson));

上面的代码产生

    ID: 30080
    Name: abc
    {
      ID: 33024
      Name: a
      {
        ID: 33024
        Name: b
        {
          ID: 33024
          Name: z
        }
      }
      ID: 4800
      Name: d
    }

现在没有任何噪音的简单磨破

    function recursiveScan(json)
    {
        if(json.dataelements.Name != null && json.id != null)
        {
            //here you have access to id and dataelements

            if(json.children.length > 0)
            {
                for(let t=0; t<json.children.length; t++)
                {
                    //here you have access to each child as json.children[t]
                    //you could do the logic for the current child

                    //then pass the current child to the recursive function
                    recursiveScan(json.children[t]);
                }
            }
        }
        return true;
    }