Skip to content

Instantly share code, notes, and snippets.

@ClementParis016
Last active December 17, 2018 16:13
Show Gist options
  • Save ClementParis016/c3cc7cec0477eeeda5f90054ebbe32aa to your computer and use it in GitHub Desktop.
Save ClementParis016/c3cc7cec0477eeeda5f90054ebbe32aa to your computer and use it in GitHub Desktop.
Get deep JavaScript Object keys with dot notation
// It may have a lot of possible use case but the one I did it for initially was
// to find which keys were missing between two JSON translations files
function getKeys(obj) {
const keys = [];
const walk = (o, parent = null) => {
for (const k in o) {
const current = parent ? parent + '.' + k : k;
keys.push(current);
// This checks if the current value is an Object
if (Object.prototype.toString.call(o[k]) === '[object Object]') {
walk(o[k], current);
}
}
}
walk(obj);
return keys;
}
/*
Exemple usage:
const obj = { some: { prop: { deeply: { nested: 'value' } }, maybe: 'not' }}
const objKeys = getKeys(obj);
// --> [ 'some', 'some.prop', 'some.prop.deeply', 'some.prop.deeply.nested', 'some.maybe' ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment