1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
|
let arr = [ { parentCode: '-1', code: '0', name: '父级1' }, { parentCode: '0', code: '1', name: '父级1-1' }, { parentCode: '0', code: '2', name: '父级1-2' }, { parentCode: '2', code: '21', name: '子级21' }, ] function buildTree (arr) { let temp = {} let tree = {} arr.forEach(item => { temp[item.code] = item })
let tempKeys = Object.keys(temp) tempKeys.forEach(key => { let item = temp[key] let _itemParentCode = item.parentCode let parentItemByParentCode = temp[_itemParentCode] if (parentItemByParentCode) { if (!parentItemByParentCode.children) { parentItemByParentCode.children = [] } parentItemByParentCode.children.push(item) } else { tree[item.code] = item } }) return Object.keys(tree).map(key => tree[key]) } console.log(buildTree (arr))
let arr = [ { date: '2020-01-06', age: '18'}, { date: '2020-01-06', age: '25'}, { date: '2020-01-07', age: '34'}, { date: '2020-01-07', age: '18'}, { date: '2020-01-07', age: '38'}, { date: '2020-01-08', age: '26'}, { date: '2020-01-09', age: '24'} ] function buildNest(arr){ let dataArr = []; arr.map(mapItem => { if (dataArr.length == 0) { dataArr.push({ date: mapItem.date, List: [mapItem] }) } else { let res = dataArr.some(item=> { if (item.date == mapItem.date) { item.List.push(mapItem) return true } }) if (!res) { dataArr.push({ date: mapItem.date, List: [mapItem] }) } } }) return dataArr } console.log(arr)
|