Skip to content

Instantly share code, notes, and snippets.

@mfalade
Last active January 16, 2020 21:40
Show Gist options
  • Save mfalade/56cc79dd8ceba57bffee455b8b001c5f to your computer and use it in GitHub Desktop.
Save mfalade/56cc79dd8ceba57bffee455b8b001c5f to your computer and use it in GitHub Desktop.
Get all the paths in an object.
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