Created
August 21, 2019 20:22
-
-
Save saintsGrad15/ae2d38a8b0b4a264eadaf288b41a3b5c to your computer and use it in GitHub Desktop.
A function that returns all paths into an arbitrarily nested javascript 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
function getObjectPaths(object, parentalPath="", delimiter=".") | |
{ | |
let paths = []; | |
for (const [key, value] of Object.entries(object)) | |
{ | |
const pathComponents = []; | |
// If 'parentalPath' doesn't indicate the root of the tree... | |
if (parentalPath.length > 0) | |
{ | |
pathComponents.push(parentalPath); | |
} | |
// Add this key to the path components | |
pathComponents.push(key); | |
// If the current value is an Array... | |
if (Array.isArray(value)) | |
{ | |
for (const element of value) | |
{ | |
// Continue to derive the path for any non-primitive values | |
if (element instanceof Object) | |
{ | |
paths = [...paths, ...getObjectPaths(element, pathComponents.join(delimiter))]; | |
} | |
} | |
// Add the path with this key once | |
paths.push(pathComponents.join(delimiter)); | |
} | |
else if (value instanceof Object) | |
{ | |
// Continue to derive the path for this Object | |
paths = [...paths, ...getObjectPaths(value, pathComponents.join(delimiter))]; | |
} | |
else | |
{ | |
// The value is a primitive, just add the path with this key | |
paths.push(pathComponents.join(delimiter)); | |
} | |
} | |
return paths; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment