简体   繁体   English

遍历复杂的嵌套json数组javascript

[英]iterate through complex nested json array javascript

nested json structure嵌套的json结构

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": {

......................... …………………………………………………………………………………………………………

I have my nested json data as shown in the image.如图所示,我有嵌套的 json 数据。 For every child object, I create a node model.对于每个子对象,我创建一个节点模型。 A child object can have additional child objects inside it.子对象内部可以有其他子对象。

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

This code handles only one level of child nodes.此代码仅处理一级子节点。 How do I check for the inner children when I don't know exactly how many child levels are nested inside?当我不知道到底有多少子级别嵌套在内部时,如何检查内部子级?

A quick run down on recursive functions and a gotcha to look out for快速了解递归函数和需要注意的问题

  • Recursive functions are great for nested data递归函数非常适合嵌套数据
  • They call themselves for each iteration of the input until it hits a base case他们为输入的每次迭代调用自己,直到达到基本情况
  • They can be tricky to wrap your head around at first一开始他们可能很难缠住你的头
  • Recursive functions can hit the call stack limit if used poorly or the input is monstrous in size如果使用不当或输入过大,递归函数可能会达到调用堆栈限制
  • Look out for variables used in the recursive calls, use let keyword to tell javascript to set the variable in the current scope注意递归调用中使用的变量,使用let关键字告诉 javascript 在当前范围内设置变量

The Solution解决方案

Let's assume your JSON has been validated and this is the structure in the example below.假设您的 JSON 已经过验证,这就是下面示例中的结构。 If I want to iterate through all elements in the JSON, I want to use a recursive call to make it neat, and simple to debug and simple to build on.如果我想遍历 JSON 中的所有元素,我想使用递归调用使其整洁、易于调试和易于构建。

Here is an example of iterating through your given example JSON to print out an exploded view.这是一个遍历给定示例 JSON 以打印出分解视图的示例。

How to use the below code如何使用以下代码

  • Copy the recursiveSearch function复制recursiveSearch函数
  • Call the recursiveSearch function passing in your JSON调用传入 JSON 的recursiveSearch函数
  • Modify it to your needs, I gave you something to build on根据您的需要修改它,我给了您一些可以构建的东西

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

The above code produces上面的代码产生

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

Now a simple run-down without all the noise现在是一个简单的破败,没有所有的噪音

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM