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
| const a = [ { id: 2, menu: "橘子", level: 2, parentId: 1, }, { id: 1, menu: "水果", level: 1, }, ];
function flat2nest(array) { const res = []; const map = {}; for (let index = 0; index < array.length; index++) { if (map[array[index].id]) { map[array[index].id] = { ...array[index], children: map[array[index].id].children, }; } else { map[array[index].id] = { ...array[index] }; } if (!array[index].parentId) { res.push(map[array[index].id]); } else { if (!map[array[index].parentId]) { map[array[index].parentId] = {}; } if (!map[array[index].parentId].children) { map[array[index].parentId].children = []; } map[array[index].parentId].children.push({ ...array[index] }); } } return res; }
const b = flat2nest(a); console.log(b);
|