需求:数组转成树状结构

image.png

  1. data: [{
  2. label: '张大大',
  3. children: [
  4. {
  5. label: '小亮',
  6. children: [{ label: '小丽' }, { label: '大光' }]
  7. }]
  8. }],

数据:

  1. const arr = [
  2. { id: '01', name: '张大大', pid: '', job: '项目经理' },
  3. { id: '02', name: '小亮', pid: '01', job: '产品leader' },
  4. { id: '03', name: '小美', pid: '01', job: 'UIleader' },
  5. { id: '04', name: '老马', pid: '01', job: '技术leader' },
  6. { id: '05', name: '老王', pid: '01', job: '测试leader' },
  7. { id: '06', name: '老李', pid: '01', job: '运维leader' },
  8. { id: '07', name: '小丽', pid: '02', job: '产品经理' },
  9. { id: '08', name: '大光', pid: '02', job: '产品经理' },
  10. { id: '09', name: '小高', pid: '03', job: 'UI设计师' },
  11. { id: '10', name: '小刘', pid: '04', job: '前端工程师' },
  12. { id: '11', name: '小华', pid: '04', job: '后端工程师' },
  13. { id: '12', name: '小李', pid: '04', job: '后端工程师' },
  14. { id: '13', name: '小赵', pid: '05', job: '测试工程师' },
  15. { id: '14', name: '小强', pid: '05', job: '测试工程师' },
  16. { id: '15', name: '小涛', pid: '06', job: '运维工程师' },
  17. { id: '16', name: '小才', pid: '07', job: '运维工程师' },
  18. ]

答案:
方法一

  1. arr.forEach(item => {
  2. // item.pid 为" "时 返回underfined
  3. let parent = obj[item.pid]
  4. if (parent) {
  5. (parent.children || (parent.children = [])).push(item)
  6. } else {
  7. // 这里push的item是pid为undefined的数据
  8. result.push(item)
  9. }
  10. })
  11. console.log(result)

方法二:用递归函数

  1. function filterArray(data, pid) {
  2. var tree = []
  3. var temp
  4. for (var i = 0; i < data.length; i++) {
  5. if (data[i].pid == pid) {
  6. var obj = data[i]
  7. temp = filterArray(data, data[i].id)
  8. if (temp.length > 0) {
  9. obj.children = temp
  10. }
  11. tree.push(obj)
  12. }
  13. }
  14. return tree
  15. }
  16. console.log(filterArray(arr, ''))