javascriptreactjsmptt

Fully mapping out object of unknown "depth" (and the most efficient way of finding the "depth" of an object)


I have a "parent" object that has an unknown "depth" of children.

My ultimate goal is to be able to fully map this "parent" object of unknown depth with all its levels of children - how would I do this?

Each child already has its "depth" associated with it as a level field, if that helps.

Am I correct to assume I have to find the "depth" of the "parent" object first (i.e. the largest "level" it contains)? What is the most efficient way of doing so?

E.g. for the object below, the "parent" object has an ultimate "depth" of 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": [],
                }
            ],
        },
    ]
}

And I would want to ultimately transform that via map in React to something like:

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

Solution

  • Looks like I don't actually need to know the depth.

    I can map out this object recursively per this answer: https://stackoverflow.com/a/61067404/4905992