Last active
July 13, 2020 06:53
-
-
Save leonidkuznetsov18/e9acae96e6e331d529ea197731ae10e3 to your computer and use it in GitHub Desktop.
convert flatten array to tree structure based on leftIndent. From Word Pargraphs.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const makeTree = (paragraphs) => { | |
| const findParentLevel = (levels, level) => { | |
| if (levels[level]) { | |
| return level; | |
| } | |
| return findParentLevel(levels, level - 1); | |
| }; | |
| const tree = paragraphs.reduce( | |
| (acc, p) => { | |
| const level = Math.abs(Math.floor(p.data.leftIndent / 18)); | |
| const levelData = { | |
| id: p.id, | |
| data: p.data, | |
| children: [], | |
| title: p.data.title, | |
| parentId: null, | |
| key: p.id, | |
| }; | |
| if (level === 0) { | |
| acc.result.push(levelData); | |
| acc.levels = { 0: levelData }; | |
| } else { | |
| const parentLevel = findParentLevel(acc.levels, level - 1); | |
| acc.levels[parentLevel].children.push({ | |
| ...levelData, | |
| parentId: acc.levels[parentLevel].id, | |
| }); | |
| acc.levels[parentLevel + 1] = levelData; | |
| } | |
| return acc; | |
| }, | |
| { result: [], levels: {} } | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment