Skip to content

Instantly share code, notes, and snippets.

@saintsGrad15
Created August 21, 2019 20:22
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 saintsGrad15/ae2d38a8b0b4a264eadaf288b41a3b5c to your computer and use it in GitHub Desktop.
Save saintsGrad15/ae2d38a8b0b4a264eadaf288b41a3b5c to your computer and use it in GitHub Desktop.
A function that returns all paths into an arbitrarily nested javascript object.
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