How does JavaScript traverse such an array of Json objects? Use recursive or loops?

for example, there is such an array of objects

let data = [
{
    title: "",
    tagName: "h1"
},
{
    title: "",
    tagName: "h1"
},
{
    title: "",
    tagName: "h2"
},
{
    title: "",
    tagName: "h3"
},
{
    title: "",
    tagName: "h2"
},
{
    title: "",
    tagName: "h1"
},
{
    title: "",
    tagName: "h1"
},
{
    title: "",
    tagName: "h2"
},
{
    title: "",
    tagName: "h3"
},
{
    title: "",
    tagName: "h3"
}
]

it is required that according to the priority of tagName, it is arranged from H1 to h6. Each H1 followed by until the next H1 is its children node, which is pushed inward in turn. For example, after the above data is processed in this way, it will look like the following format:

let data = [
    {
      title: "",
      tagName: "h1"
    },
    {
      title: "",
      tagName: "h1",
      children: [
        {
          title: "",
          tagName: "h2"
          children: [
             {
                 title: "",
                 tagName: "h3"
             }
          ]
        },
        {
          title: "",
          tagName: "h2"
        }
      ]
    },
    {
      title: "",
      tagName: "h1"
    },
    {
      title: "",
      tagName: "h1",
      children: [
        {
          title: "",
          tagName: "h2",
          children: [
            {
              title: "",
              tagName: "h3"
            },
            {
              title: "",
              tagName: "h3"
            }
          ]
        }
      ]
    }
]

how to write such a traversal algorithm? Ask the boss for advice


function collect(arr, i, parent) {
    if (i >= arr.length) {
        return i
    }
    let current = arr[i]
    if (current.tagName > parent.tagName) {
        parent.children.push(current)
    } else {
        return i
    }
    iPP
    let next = arr[i]
    if (!next) {
        return i
    }
    if (next.tagName > current.tagName) {
        current.children = []
        i = collect(arr, i, current)
    }
    return collect(arr, i, parent)
}

var ret = {
    tagName: 'h0',
    children: []
}
collect(data, 0, ret)

console.log(ret.children)

@ yuanxiaowa I'd like to ask you again. How to write the formatted results if you want to traverse them sequentially. It is equivalent to traversing each object in the result array to print the output in the order of the original object:

{
    title: '',
    tagName: 'h1'
},
{
    title: '',
    tagName: 'h1'
},
{
    title: '',
    tagName: 'h2'
},
{
    title: '',
    tagName: 'h3'
},
{
    title: '',
    tagName: 'h2'
},
{
    title: '',
    tagName: 'h1'
},
{
    title: '',
    tagName: 'h1'
},
{
    title: '',
    tagName: 'h2'
},
{
    title: '',
    tagName: 'h3'
},
{
    title: '',
    tagName: 'h3'
}
Menu