js 将数组铺平,并且子子级携带所有父级数据

110 阅读1分钟

``

data() {
      return {
      
        beforeTree: [
          {
            a: 1,
            b: 2,
            list: [
              {
                c: 3,
                d: 4,
                e: 5
              },
              {
                c: 3,
                d: 4,
                e: 5,
                list: [
                  {
                    f: 1,
                    g: 2,
                    z: 3
                  }
                ]
              }
            ]
          },
          {
            a: 3,
            b: 2,
            list: [
              {
                c: 3,
                d: 4,
                e: 5
              },
              {
                c: 3,
                d: 4,
                e: 5,
                list: [
                  {
                    f: 5,
                    g: 6,
                    z: 7
                  }
                ]
              }
            ]
          }
        ],
        afterTree: [],
      }
      
      //=========三层以内==============================
      changeTree() {
        this.afterTree = []
        this.beforeTree.forEach(item => {
          if (Array.isArray(item.list) && item.list.length){
            item.list.forEach(mItem => {
              mItem.a = item.a
              mItem.b = item.b
              if (Array.isArray(mItem.list) && mItem.list.length){
                mItem.list.forEach(lItem => {
                  lItem.a = mItem.a
                  lItem.b = mItem.b
                  lItem.c = mItem.c
                  lItem.d = mItem.d
                  lItem.e = mItem.e
                  this.afterTree.push(lItem)
                })
              }else{
                this.afterTree.push(mItem)
              }
            })
          }else{
            this.afterTree.push(item)
          }

        })
        console.log(this.beforeTree,'beforeTree')
        console.log(this.afterTree,'afterTree')
      },