【问题标题】:Fully mapping out object of unknown "depth" (and the most efficient way of finding the "depth" of an object)完全映射出未知“深度”的对象(以及找到对象“深度”的最有效方法)
【发布时间】:2021-05-10 23:54:49
【问题描述】:

我有一个“父级”对象,它的子级“深度”未知。

我的最终目标是能够完全map这个深度未知的“父”对象及其所有级别的子对象 - 我将如何做到这一点?

如果有帮助的话,每个孩子都已经将其“深度”作为level 字段与之关联。

我是否正确假设我必须首先找到“父”对象的“深度”(即它包含的最大“级别”)?这样做最有效的方法是什么?

例如对于下面的对象,“父”对象的最终“深度”为 2。

{
    "title": "parent",
    "level": 0,
    "children": [
        {
            "title": "foo",
            "level": 1,
            "children": [],
        },
        {
            "title": "foo1",
            "level": 1,
            "children": [],
        },
        {
            "title": "foo2",
            "level": 1,
            "children": [
                {
                    "title": "foo3",
                    "level": 2,
                    "children": [],
                }
            ],
        },
    ]
}

我希望最终通过 map 在 React 中将其转换为:

<h1>parent</h1>
<h2>foo</h2>
<h2>foo1</h2>
<h2>foo2</h2>
<h3>foo3</h3>

【问题讨论】:

    标签: javascript reactjs mptt


    【解决方案1】:

    看起来我实际上不需要知道深度。

    我可以根据这个答案递归地绘制这个对象:https://stackoverflow.com/a/61067404/4905992

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      • 2014-07-06
      • 2016-01-19
      • 2020-10-17
      • 1970-01-01
      • 2021-03-20
      • 2011-08-04
      相关资源
      最近更新 更多