【问题标题】:iterate through complex nested json array javascript遍历复杂的嵌套json数组javascript
【发布时间】:2018-07-09 21:06:03
【问题描述】:

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);
    }
}

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

【问题讨论】:

  • 请创建一个minimal reproducible example。我们不会将您的json数据从图片写入代码
  • 你可以使用递归来迭代你的对象
  • 你能分享一下JSON吗
  • 内部孩子的数量是可变的。如何迭代或什么可以是可迭代的条件?

标签: javascript arrays json loops


【解决方案1】:

递归函数的简要介绍和需要注意的问题

  • 递归函数非常适合嵌套数据
  • 他们在输入的每次迭代中调用自己,直到达到基本情况
  • 一开始可能很难缠住你的头
  • 如果使用不当或输入过大,递归函数可能会达到调用堆栈限制
  • 注意递归调用中使用的变量,使用 let 关键字告诉 javascript 在当前范围内设置变量

解决方案

假设您的 JSON 已经过验证,这就是下面示例中的结构。 如果我想遍历 JSON 中的所有元素,我想使用递归调用使其整洁、易于调试和易于构建。

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

如何使用下面的代码

  • 复制recursiveSearch函数
  • 调用传入 JSON 的 recursiveSearch 函数
  • 根据您的需要修改它,我给了您一些可以构建的东西

代码

    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;
    }

【讨论】:

    猜你喜欢
    • 2017-10-16
    • 2021-06-16
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多