1. //从后台获取的对象数组,根据对象的type进行分组合并成tree树形展示数据
    2. const dataArr = [
    3. { type: '治理层', name: 'hive_82', reserve: '2', id: 1 },
    4. { type: '原始数据层', name: 'qwe', reserve: '1', id: 2 },
    5. { type: '贴源层', name: 'mysql_exchangis', reserve: '3', id: 3 },
    6. { type: '治理层', name: 'links_188', reserve: '1', id: 4 },
    7. { type: '贴源层', name: 'mysql_ces', reserve: '2', id: 5 }
    8. ]
    9. const treeData = dataArr.reduce((cur, next) => {
    10. const obj = cur.find(curItem => curItem.label === next.type)
    11. if (obj) {
    12. if (obj.children.indexOf(next.id) === -1) { //去重处理
    13. // console.log(obj.children.indexOf(next.id))
    14. obj.children.push({
    15. ...next,
    16. label: next.name
    17. })
    18. }
    19. } else {
    20. const newObj = {
    21. label: next.type,
    22. children: [{
    23. ...next,
    24. label: next.name
    25. }]
    26. }
    27. cur.push(newObj)
    28. }
    29. return cur
    30. }, [])
    31. console.log(treeData)
    32. // 合并后的结果:
    33. let resultData = [
    34. {
    35. label: '治理层',
    36. children: [
    37. { type: '治理层', name: 'hive_82', reserve: '2', id: 1, label: 'hive_82' },
    38. { type: '治理层', name: 'links_188', reserve: '1', id: 4, label: 'links_188' }
    39. ]
    40. },
    41. {
    42. label: '原始数据层',
    43. children: [
    44. { type: '原始数据层', name: 'qwe', reserve: '1', id: 2, label: 'qwe' }
    45. ]
    46. },
    47. {
    48. label: '贴源层',
    49. children: [
    50. { type: '贴源层', name: 'mysql_exchangis', reserve: '3', id: 3, label: 'mysql_exchangis' },
    51. { type: '治理层', name: 'mysql_ces', reserve: '2', id: 5, label: 'mysql_ces' }
    52. ]
    53. }
    54. ]
    55. // let list = [{name:'wxq'},{name:'wxq1'}]
    56. // console.log(list.indexOf({name:'wxq'})