Created
December 10, 2016 02:31
-
-
Save kaw2k/1e82fff14d0b030c9ccc92a9d46a4f3b to your computer and use it in GitHub Desktop.
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 setPath = (value, path, json) => { | |
// We reached the end, return the value as a leaf | |
if (!path.length) return value | |
// Figure out if we are going down an array or object | |
const isArrayMatch = path[0].match(/^\[(\d+)\]$/) | |
const name = isArrayMatch ? isArrayMatch[1] : path[0] | |
// Add the value to our json recursivly | |
json = json || (isArrayMatch ? [] : {}) | |
json[name] = setPath(value, path.slice(1), json[name]) | |
return json | |
} | |
const inflateTreeArray = (prop, treeArray) => { | |
return treeArray.reduce( | |
(tree, node) => setPath(node[prop], node.path.split('.'), tree), | |
{} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment