Last active
January 17, 2017 02:53
-
-
Save rmdort/50130f0d9f2d1639082539c6b16781d0 to your computer and use it in GitHub Desktop.
Solr path hierarchy to Javascript object
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
| function toNestedArray (data, rootLevel = 0, parentNode) { | |
| let output = [] | |
| for (var i = 0; i < data.length; i++) { | |
| var count = data[i].count | |
| var items = data[i].name.split('/') | |
| var hasParent = items.length > rootLevel | |
| if (hasParent) { | |
| let parent = rootLevel | |
| ? items.length === rootLevel | |
| ? null | |
| : items.slice(0, items.length - 1).join('/') || null | |
| : items.slice(0, items.length - 1).join('/') || null | |
| output.push({ | |
| displayName: items.pop(), | |
| count, | |
| parent, | |
| name: data[i].name | |
| }) | |
| } | |
| } | |
| function getNestedChildren (arr, parent) { | |
| var out = [] | |
| for (let i in arr) { | |
| if (arr[i].parent === parent) { | |
| var children = getNestedChildren(arr, arr[i].name) | |
| if (children.length) { | |
| arr[i].children = children | |
| } | |
| out.push(arr[i]) | |
| } | |
| } | |
| return out | |
| } | |
| return getNestedChildren(output, parentNode === '' ? null : parentNode) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment