Last active
January 16, 2020 21:40
-
-
Save mfalade/56cc79dd8ceba57bffee455b8b001c5f to your computer and use it in GitHub Desktop.
Get all the paths in an object.
This file contains 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 isPlainObject from 'lodash/isPlainObject'; | |
function canTraverseNodes(obj) { | |
return isPlainObject(obj) || (Array.isArray(obj) && isPlainObject(obj[0])); | |
} | |
function getAllPaths(obj, basePath = '', paths = []) { | |
if (!canTraverseNodes(obj)) { | |
return paths; | |
} | |
return Object.keys(obj).reduce((accumulator, next) => { | |
const currentPath = basePath ? `${basePath}.${next}` : next; | |
const nextObj = obj[next]; | |
if (isEmpty(nextObj)) { | |
return accumulator; | |
} | |
if (canTraverseNodes(nextObj)) { | |
getAllPaths(nextObj, currentPath, accumulator); | |
} else { | |
accumulator.push(currentPath); | |
} | |
return accumulator; | |
}, paths); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment