JavaScript怎么遍历这样的一个Json的对象数组?用递归or循环?

csdoker
  • 510

比如有这样一个对象数组

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'
}
]

要求根据tagName的优先级,从h1开始排,一直到h6,每个h1后面直到下个h1之前的都是它的children节点,依次内推,比如上面的数据这样处理后就会像下面的格式:

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'
            }
          ]
        }
      ]
    }
]

怎么写这样的一个遍历算法呢?求大佬指教

回复
阅读 3.2k
2 个回答
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
    }
    i++
    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 想再问下你。。如果要顺序遍历处理好格式的结果 怎么写呢。。。就相当于遍历结果数组的每一个对象 按照原来对象的顺序打印输出:

{
    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'
}
你知道吗?

宣传栏