用这个网站来测试代码
const tree = [ { name: "one", id: "1", list: [ { name: "oneOne", id: "11", list: [{ name: "oneOneOne", id: "111" }] }, { name: "oneTwo", id: "12", list: [ { name: "oneTwoOne", id: "121" }, { name: "oneTwoTwo", id: "122" }, { name: "oneTwoThree", id: "123" }, ], }, ], }, { name: "two", id: "2", list: [ { name: "twoOne", id: "21", list: [{ name: "twoOneOne", id: "211" }] }, { name: "twoTwo", id: "22", list: [ { name: "twoTwoOne", id: "221" }, { name: "twoTwoTwo", id: "222" }, ], }, ], }, ]; const flatten = ( children: any[], parentId?: string | number, parentName?: string, level = 1, parentNodes?: any[] ) => Array.prototype.concat.apply( children.map((x) => ({ // ...x, name: x.name, id: x.id, parentId, parentName, level, parentNodes: JSON.parse(JSON.stringify(parentNodes || [])), })), children.map((x) => flatten( x.list || [], x.id, x.name, (level || 1) + 1, Array.isArray(parentNodes) ? [...parentNodes, { id: x.id, name: x.name }] : x.id !== undefined ? [{ id: x.id, name: x.name }] : [] ) ) ); const flat = flatten(tree); console.log(flat);
const flat = [ { name: "one", id: "1", parentId: undefined, parentName: undefined, }, { name: "two", id: "2", parentId: undefined, parentName: undefined, }, { name: "oneOne", id: "11", parentId: "1", parentName: "one", }, { name: "oneTwo", id: "12", parentId: "1", parentName: "one", }, { name: "oneOneOne", id: "111", parentId: "11", parentName: "oneOne", }, { name: "oneTwoOne", id: "121", parentId: "12", parentName: "oneTwo", }, { name: "oneTwoTwo", id: "122", parentId: "12", parentName: "oneTwo", }, { name: "oneTwoThree", id: "123", parentId: "12", parentName: "oneTwo", }, { name: "twoOne", id: "21", parentId: "2", parentName: "two", }, { name: "twoTwo", id: "22", parentId: "2", parentName: "two", }, { name: "twoOneOne", id: "211", parentId: "21", parentName: "twoOne", }, { name: "twoTwoOne", id: "221", parentId: "22", parentName: "twoTwo", }, { name: "twoTwoTwo", id: "222", parentId: "22", parentName: "twoTwo", }, ]; const buildTree = (data: typeof flat) => data .reduce( (m, { id, name, parentId }) => ( m.get(parentId)!.push({ id, name, list: m.set(id, []).get(id) }), m ), new Map<string | undefined, any[]>([[undefined, []]]) ) .get(undefined); const tree = buildTree(flat); console.log(tree);
点击这里前往 Github 查看原文,交流意见~
文档信息
版权声明:自由转载 - 非商用 - 非衍生 - 保持署名(创意共享3.0许可证)