Skip to content

Instantly share code, notes, and snippets.

@YanivHaramati
Created April 9, 2015 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YanivHaramati/dc8b61e7105fd3a6e985 to your computer and use it in GitHub Desktop.
Save YanivHaramati/dc8b61e7105fd3a6e985 to your computer and use it in GitHub Desktop.
get all keys from an object, nested or otherwise.
Array.prototype.flatten = function () {
return this.reduce(function (all, current) {
if (current.constructor === Array) return all.concat(current.flatten());
else return all.concat(current);
},[]);
}
function getAllKeys(obj) {
return Object.keys(obj).reduce(function (allKeys, key) {
var val = obj[key];
if (val.constructor === Array) {
allKeys.push(key);
allKeys = allKeys.concat(val.map(getAllKeys).flatten());
} else {
allKeys.push(key);
var nestedKeys = Object.keys(val);
if (nestedKeys.length)
allKeys = allKeys.concat(getAllKeys(val));
}
return allKeys;
}, []);
}
// test
getAllKeys({'a':1, 'b':{'c':2}, 'd': [{'e': 3}, { 'f': { 'g': 4 } }], 'h': [1,2,3]})
// should return: ["a", "b", "c", "d", "e", "f", "g", "h"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment