Skip to content

Instantly share code, notes, and snippets.

@kaw2k
Created December 10, 2016 02:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaw2k/1e82fff14d0b030c9ccc92a9d46a4f3b to your computer and use it in GitHub Desktop.
Save kaw2k/1e82fff14d0b030c9ccc92a9d46a4f3b to your computer and use it in GitHub Desktop.
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