Last active
September 3, 2018 16:31
-
-
Save srph/485973308e9a4ebced1c0eda7c419435 to your computer and use it in GitHub Desktop.
JS: Flatten tree
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
import React from "react"; | |
import ReactDOM from "react-dom"; | |
import tree from "./Tree.json"; | |
const flattenTree = tree => { | |
let newData = []; | |
const flattenFn = (node) => { | |
if (node.child && node.child.length) { | |
node.child.forEach(subNode => { | |
flattenFn(subNode); | |
}); | |
} | |
const newNode = { ...node }; | |
delete newNode.child; | |
newData.push(newNode); | |
}; | |
flattenFn(tree); | |
return newData; | |
}; | |
const output = JSON.stringify(flattenTree(tree), null, " "); | |
const rootElement = document.getElementById("root"); | |
ReactDOM.render(<pre>{output}</pre>, rootElement); |
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
{ | |
"id": 1, | |
"name": "sample 1", | |
"child": [ | |
{ | |
"id": 12, | |
"name": "sample 12", | |
"child": [], | |
"parentId": 1 | |
}, | |
{ | |
"id": 13, | |
"name": "sample 13", | |
"child": [], | |
"parentId": 1 | |
}, | |
{ | |
"id": 14, | |
"name": "sample 14", | |
"child": [], | |
"parentId": 1 | |
}, | |
{ | |
"id": 2, | |
"name": "sample 2", | |
"child": [ | |
{ | |
"id": 22, | |
"name": "sample 22", | |
"parentId": 2, | |
"child": [ | |
{ | |
"id": 222, | |
"name": "sample 222", | |
"child": [], | |
"parentId": 22 | |
}, | |
{ | |
"id": 223, | |
"name": "sample 223", | |
"child": [], | |
"parentId": 22 | |
}, | |
{ | |
"id": 224, | |
"name": "sample 224", | |
"parentId": 22, | |
"child": [ | |
{ | |
"id": 2242, | |
"name": "here dito", | |
"child": [], | |
"parentId": 224 | |
}, | |
{ | |
"id": 2232, | |
"name": "sample 2232", | |
"child": [], | |
"parentId": 224 | |
}, | |
{ | |
"id": 2244, | |
"name": "sample 2244", | |
"child": [], | |
"parentId": 224 | |
} | |
] | |
} | |
] | |
}, | |
{ | |
"id": 23, | |
"name": "sample 23", | |
"child": [], | |
"parentId": 2 | |
}, | |
{ | |
"id": 24, | |
"name": "sample 24", | |
"child": [], | |
"parentId": 2 | |
} | |
] | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment