Last active
May 3, 2017 19:42
-
-
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
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 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