Skip to content

Instantly share code, notes, and snippets.

@hafbau
Created August 8, 2018 19:35
Show Gist options
  • Save hafbau/a624b4ebaca18d4743a685131e3d2eff to your computer and use it in GitHub Desktop.
Save hafbau/a624b4ebaca18d4743a685131e3d2eff to your computer and use it in GitHub Desktop.
const createKeyPath = function (currentKeyPath, key) {
return currentKeyPath + (currentKeyPath ? '.' : '') + key;
};
function recursiveObjectKeysPaths(obj, path = '') {
if (!obj || typeof obj == 'string') return;
let keys = [];
let currentPath;
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i += 1) {
currentPath = createKeyPath(path, (i).toString());
const subKeys = recursiveObjectKeysPaths(obj[i], currentPath);
if (subKeys && Array.isArray(subKeys) && subKeys.length) currentPath = subKeys
keys = keys.concat(currentPath);
}
} else {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
currentPath = createKeyPath(path, key);
const subKeys = recursiveObjectKeysPaths(obj[key], currentPath);
if(subKeys && Array.isArray(subKeys) && subKeys.length) currentPath = subKeys
keys = keys.concat(currentPath);
}
}
}
return keys;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment