「已注销」 2021-04-28 18:30 采纳率: 71.4%
浏览 440
已采纳

vue.js数组中有多个子级,怎么把他们全部拼接到单个数组同一级中

[
    {
      "id": 1,
      "title": "1",
      "children": [
        {
          "id": 2,
          "title": "1.1",
        },
        {
          "id": 3,
          "title": "1.2",
        },
        {
          "id": 4,
          "title": "1.3",
          "children": [],
        },
        {
          "id": 5,
          "title": "1.4",
					"children": [
            {
              "id": 6,
          		"title": "1.4.1",
              "children": [],
            },
              {
              "id": 7,
          		"title": "1.4.2",
            }
          ],
        },
        {
          "id": 8,
          "title": "1.5",
        }
      ]
    },
    {
      "id": 2,
      "title": "2",
      "children": [],
    }
  ],
  • 写回答

5条回答 默认 最新

  • 关注

     item.children.length > 0改为item.children && item.children.length > 0即可,仅判断item.children.length > 0可能会存在item.children不存在,导致item.children.length报错undifined。基本就是雨生百谷老铁的代码 

    export function FlatArray (data) {
      console.log('原数组长度:', data.length)
      if (data.length === 0) {
        return []
      }
      let arr = []
      data.map((item) => {
        if (item.children && item.children.length > 0) {
          arr = arr.concat(FlatArray(item.children))
        } else {
          item.children = []
        }
        arr.push(item)
      })
      console.log('打平后数组长度:', arr.length)
      return arr
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?