【问题标题】:Javascript - Couting all nested objects of JSONJavascript - 计算 JSON 的所有嵌套对象
【发布时间】:2017-06-18 10:12:22
【问题描述】:

假设我有以下 JSON:

{
  "id": "foo",
  "list": [
    {
      "id": "A",
      "list": [
        {
          "id": "B",
          "list": [
            {
              "id": "C",
              "list": [
                {
                  "id": "D",
                  "list": []
                },
                {
                  "id": "E",
                  "list": []
                }
              ]
            },
            {
              "id": "F",
              "list": []
            },
            {
              "id": "G",
              "list": [
                {
                  "id": "H",
                  "list": []
                },
                {
                  "id": "I",
                  "list": []
                },
                {
                  "id": "J",
                  "list": []
                }
              ]
            }
          ]
        },
        {
          "id": "K",
          "list": []
        }
      ]
    },
    {
      "id": "L",
      "list": [
        {
          "id": "M",
          "list": []
        }
      ]
    },
    {
      "id": "N",
      "list": []
    },
    {
      "id": "O",
      "list": [
        {
          "id": "P",
          "list": [
            {
              "id": "Q",
              "list": []
            },
            {
              "id": "R",
              "list": []
            },
            {
              "id": "S",
              "list": []
            },
            {
              "id": "T",
              "list": [
                {
                  "id": "U",
                  "list": []
                }
              ]
            },
            {
              "id": "V",
              "list": [
                {
                  "id": "W",
                  "list": [
                    {
                      "id": "X",
                      "list": []
                    },
                    {
                      "id": "Y",
                      "list": []
                    },
                    {
                      "id": "Z",
                      "list": []
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}

我的问题是:我如何计算每个孩子并将这个数字附加到每个对象的属性中?

例子:

  • “C”对象在子对象“D”和“E”内部和之上有 2 个对象。
  • “W”对象在子对象内部和之上有 3 个对象,“X”、“Y”和“Z”。
  • “V”对象有(这是诀窍)在子对象内部和子对象上的 4 个对象,“W”对象本身及其所有子对象(3前面提到的)。

关于这个,“C”对象应该有一个属性,我们将其命名为“allBelow”,包含数字2。“W”对象包含3,“V”对象包含4。以此类推,对于每个对象。

我想知道一些递归函数可以完成这项工作,但我没有实现。

你能帮帮我吗?

最佳,

【问题讨论】:

    标签: javascript json recursion traversal


    【解决方案1】:

    var myObj = {"id":"foo","list":[{"id":"A","list":[{"id":"B","list":[{"id":"C","list":[{"id":"D","list":[]},{"id":"E","list":[]}]},{"id":"F","list":[]},{"id":"G","list":[{"id":"H","list":[]},{"id":"I","list":[]},{"id":"J","list":[]}]}]},{"id":"K","list":[]}]},{"id":"L","list":[{"id":"M","list":[]}]},{"id":"N","list":[]},{"id":"O","list":[{"id":"P","list":[{"id":"Q","list":[]},{"id":"R","list":[]},{"id":"S","list":[]},{"id":"T","list":[{"id":"U","list":[]}]},{"id":"V","list":[{"id":"W","list":[{"id":"X","list":[]},{"id":"Y","list":[]},{"id":"Z","list":[]}]}]}]}]}]};
    
    function count(obj) {
      var c = obj.list.length;
      c += obj.list.reduce((a, e) => a + count(e), 0);
      obj.count = c; // assign the count after counting the subobjects.
      return c; // return the count to be used by parent objects
    }
    
    count(myObj);
    
    console.log(myObj);

    【讨论】:

    • 非常感谢@ibrahim-mahrir !!!有效!现在我要花一些时间来理解它!大声笑尽管如此,我还是做了回复以向其他用户澄清repl.it/F3Tk/0
    • @LeandroFerreiraFernandes 不客气!那些叫做箭头函数,我前几天才学的。他们太棒了。 here 是来自 Mozilla 的关于它们的快速参考。当你学会它们时,你会发现它们有多酷。
    • @ibrahimmahrir 我已经在好书eloquentjavascript.net 上看到了这个函数,但我仍然渴望一些晚上来研究它!非常感谢您的贡献!!! o/
    【解决方案2】:

    递归函数是个好主意。试试这个:

    var data = {"id":"foo","list":[{"id":"A","list":[{"id":"B","list":[{"id":"C","list":[{"id":"D","list":[]},{"id":"E","list":[]}]},{"id":"F","list":[]},{"id":"G","list":[{"id":"H","list":[]},{"id":"I","list":[]},{"id":"J","list":[]}]}]},{"id":"K","list":[]}]},{"id":"L","list":[{"id":"M","list":[]}]},{"id":"N","list":[]},{"id":"O","list":[{"id":"P","list":[{"id":"Q","list":[]},{"id":"R","list":[]},{"id":"S","list":[]},{"id":"T","list":[{"id":"U","list":[]}]},{"id":"V","list":[{"id":"W","list":[{"id":"X","list":[]},{"id":"Y","list":[]},{"id":"Z","list":[]}]}]}]}]}]};
    
    function addCount(node) {
      node.count = 0;
      for (var i = 0; i < node.list.length; i++) {
        var child = node.list[i];
        addCount(child);
        node.count += child.count + 1;
      }
    }
    
    addCount(data);
    console.log(data)

    它首先在每个子节点上调用自己。然后它将每个孩子添加到计数中,即 1 + 孙辈(或孙辈或更多)的数量。

    【讨论】:

      【解决方案3】:

      深度优先搜索应该可行,我在想这样的事情(未经测试的代码):

      function DFS(tree){
          var currentCount = tree.list.length;
          for(var i=0;i<count;i++){
              currentCount += DFS(tree.list[i]);
          }
          tree["count"] = currentCount;
          return currentCount;
      }
      

      【讨论】:

      • 这里只计算直子的数量
      • 这不是他要求的。请参阅“V”对象在子对象内部和子对象上有 4 个对象(这是诀窍),“W”对象本身及其所有子对象(前面提到的 3 个)
      • 诀窍是强制代码“向后”迭代,如果你明白我的意思的话。
      • 哦,我明白了,我不明白它必须计算每个孩子。好的,让我解决它...
      【解决方案4】:

      你可以做一个简单的 DFS:

      function appendNumChildren(currentNode) {  
        const totalChildren = currentNode.list.reduce((acc, node) => {
          return acc + appendNumChildren(node);
        }, 0)
      
        currentNode.allBelow = totalChildren;
      
        return totalChildren + 1;
      }
      
      appendNumChildren(json);
      

      https://jsbin.com/qekabatuwi/edit?js,console

      【讨论】:

        猜你喜欢
        • 2017-11-24
        • 2017-02-14
        • 1970-01-01
        • 2015-04-23
        • 2016-09-27
        • 2020-02-21
        • 1970-01-01
        • 2011-12-02
        • 1970-01-01
        相关资源
        最近更新 更多