Skip to content

Instantly share code, notes, and snippets.

@selvagsz
Last active October 24, 2016 08:28
Show Gist options
  • Save selvagsz/12cccbf524476b0e5cdf166c4578323b to your computer and use it in GitHub Desktop.
Save selvagsz/12cccbf524476b0e5cdf166c4578323b to your computer and use it in GitHub Desktop.
let a = {
name: 'selva'
}
let zfoo = {
foo: {
name: 'a',
ofo: {
bar: a
}
},
bar: false
}
// findFilePath(zfoo, a)
// => foo/ofo/bar
export const findFilePath = (root, value) => {
let paths = ['']
let found = false
function traverse(tree) {
Object.keys(tree).some((node) => {
if (found) {
return true
}
let subtree = tree[node]
if (subtree === value) {
paths.push(node)
found = true
return true
}
if (typeof subtree === 'object' && subtree.toString() === '[object Object]') {
paths.push(node)
traverse(subtree)
}
})
if (!found) paths.pop()
}
traverse(root)
return paths.join('/')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment