js中把普通json轉換爲樹形json

利用遞歸方法:app

1.數據格式一 ARRthis

var ARR = [
  {
    content: { id: 10, parentId: -1, name: '紅色', code: 'red' },
    children: [
      {
        content: { id: 11, parentId: 10, name: '紅蘋果', code: 'red.apple' },
        children: []
      },
      {
        content: { id: 12, parentId: 10, name: '紅火龍果', code: 'red.pitaya' },
        children: []
      },
      {
        content: { id: 13, parentId: 10, name: '紅櫻桃', code: 'red.cherry' },
        children: []
      }
    ]
  },
  {
    content: { id: 20, parentId: -1, name: '綠色', code: 'green' },
    children: [
      {
        content: { id: 21, parentId: 20, name: '綠棗', code: 'green.jujube' },
        children: []
      },
      {
        content: { id: 22, parentId: 20, name: '綠檸檬', code: 'green.lemon' },
        children: []
      }
    ]
  },
  {
    content: { id: 30, parentId: -1, name: '黃色', code: 'yellow' },
    children: []
  }
]

2.數據格式二 BRRcode

var BRR = [
  {
    id: 10,
    parentId: -1,
    name: '紅色',
    code: 'red',
    children: [
      { id: 11, parentId: 10, name: '紅蘋果', code: 'red.apple', children: [] },
      { id: 12, parentId: 10, name: '紅火龍果', code: 'red.pitaya', children: [] },
      { id: 13, parentId: 10, name: '紅櫻桃', code: 'red.cherry', children: [] }
    ]
  },
  {
    id: 20,
    parentId: -1,
    name: '綠色',
    code: 'green',
    children: [
        { id: 21, parentId: 20, name: '綠棗', code: 'green.jujube', children: [] }, 
        { id: 22, parentId: 20, name: '綠檸檬', code: 'green.lemon', children: [] }
    ]
  },
  {
    id: 30,
    parentId: -1,
    name: '黃色',
    code: 'yellow',
    children: []
  }
]

3.目的:將ARR數據格式轉換爲BRR數據格式遞歸

methods: {
    getMemberTable() {
      getPermission().then(res => {
        let ARR = res.data.content
        var CRR = []
        this.fn(ARR, CRR)
        console.log('ARR:', ARR)
        console.log('CRR:', CRR)
        this.dataList = CRR
        console.log('dataList:', this.dataList)
      })
    },
    fn(data, newArr) {
      // console.log('data1:', data)
      // console.log('newArr1:', newArr)
      data.forEach((item, index) => {
        newArr[index] = item.content
        newArr[index].children = item.children
        if (item.children == []) return
        this.fn(item.children, newArr[index].children)
      })
    },
  }

4.注:若有多處需轉換,可將fn註冊到全局get

相關文章
相關標籤/搜索