Last active
December 17, 2018 16:13
-
-
Save ClementParis016/c3cc7cec0477eeeda5f90054ebbe32aa to your computer and use it in GitHub Desktop.
Get deep JavaScript Object keys with dot notation
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
// 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