加载中... JS线性数据转化成树形数据 - semyin's blog
7°

JS线性数据转化成树形数据

给出如下Array

const arr = [
  {
    id: 1,
    name: '广东省',
    parentId: 0
  },
  {
    id: 2,
    parentId: 1,
    name: '深圳市'
  },
  {
    id: 3,
    parentId: 2,
    name: '南山区'
  },
  {
    id: 5,
    parentId: 1,
    name: '广州市'
  },
  {
    id: 6,
    parentId: 5,
    name: '越秀区'
  },
  {
    id: 7,
    parentId: 0,
    name: '江西省'
  },
  {
    id: 8,
    parentId: 7,
    name: '赣州市'
  },
  {
    id: 9,
    parentId: 0,
    name: '上海市'
  },
  {
    id: 10,
    parentId: 9,
    name: '宝山区'
  },
  {
    id: 11,
    parentId: 0,
    name: '河南省'
  }
]

要求:转化成如下的tree结构数据

const target = [
  {
    id: 1,
    name: '广东省',
    parentId: 0,
    children: [
      {
        id: 2,
        parentId: 1,
        name: '深圳市',
        children: [
          {
            id: 3,
            parentId: 2,
            name: '南山区'
          }
        ]
      },
      {
        id: 5,
        parentId: 1,
        name: '广州市',
        children: [
          {
            id: 6,
            parentId: 5,
            name: '越秀区'
          }
        ]
      }
    ]
  },
  {
    id: 7,
    parentId: 0,
    name: '江西省',
    children: [
      {
        id: 8,
        parentId: 7,
        name: '赣州市'
      }
    ]
  },
  {
    id: 9,
    parentId: 0,
    name: '上海市',
    children: [
      {
        id: 10,
        parentId: 9,
        name: '宝山区'
      }
    ]
  },
  {
    id: 11,
    parentId: 0,
    name: '河南省'
  }
]

实现方法
两次暴力遍历

function covert(array) {
  let resultArray = array.filter(item => {
    let children = array.filter(child => {
      return item.id === child.parentId
    })
    item.children = children
    return item.parentId === 0
  })
  return resultArray
}

convert(arr)


已有 0 条评论

    我有话说: