簡體   English   中英

遍歷復雜的嵌套json數組javascript

[英]iterate through complex nested json array javascript

嵌套的json結構

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

此代碼僅處理一級子節點。 當我不知道到底有多少子級別嵌套在內部時,如何檢查內部子級?

快速了解遞歸函數和需要注意的問題

  • 遞歸函數非常適合嵌套數據
  • 他們為輸入的每次迭代調用自己,直到達到基本情況
  • 一開始他們可能很難纏住你的頭
  • 如果使用不當或輸入過大,遞歸函數可能會達到調用堆棧限制
  • 注意遞歸調用中使用的變量,使用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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM