Created
November 14, 2013 18:20
-
-
Save iskugor/7471711 to your computer and use it in GitHub Desktop.
Get unique keys in nested object
This file contains hidden or 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
function getKeys(obj) { | |
var keys = Object.keys(obj); | |
keys.forEach(function(val) { | |
if (obj[val] instanceof Object) { | |
keys = keys.concat(getKeys(obj[val])); | |
} | |
}); | |
return keys; | |
} | |
function getUniqueKeys(obj) { | |
var keys = getKeys(obj); | |
keys = keys.filter(function (e, i, keys) { | |
return keys.lastIndexOf(e) === i; | |
}); | |
return keys; | |
} | |
alert(getUniqueKeys({ | |
key1: 'one', | |
key2: { | |
key1: { | |
another: 42 | |
} | |
} | |
})); //produces "key2,key1,another" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment