Skip to content

Instantly share code, notes, and snippets.

@AaronHarris
Last active May 3, 2017 19:42
Show Gist options
  • Save AaronHarris/230579a128bad9d876ba2cc41d9d0771 to your computer and use it in GitHub Desktop.
Save AaronHarris/230579a128bad9d876ba2cc41d9d0771 to your computer and use it in GitHub Desktop.
Gets all the properties you can call on an arbitrary JavaScript object and its prototype chain
function logAllProperties(obj) {
if (obj == null) return; // recursive approach
console.log(Object.getOwnPropertyNames(obj));
logAllProperties(Object.getPrototypeOf(obj));
}
// logAllProperties(my_object);
// Using this, you can also write a function that returns you an array of all the property names:
function props(obj) {
var p = [];
for (; obj != null; obj = Object.getPrototypeOf(obj)) {
var op = Object.getOwnPropertyNames(obj);
for (var i=0; i<op.length; i++)
if (p.indexOf(op[i]) == -1)
p.push(op[i]);
}
return p;
}
// console.log(props(my_object));
// or, get fancy with generators
function* propIter(obj) {
for (; obj != null; obj = Object.getPrototypeOf(obj)) {
yield Object.getOwnPropertyNames(obj); // or yield* for a flat output structure
}
}
// [...propIter(obj)] or Array.from(propIter(obj))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment