Reputation: 35813
I have a Javascript object (it happens to be the database
object from the CloudKit library, but that's not important). As per How to get all properties values of a Javascript Object (without knowing the keys)? I have tried the following to list this object's keys:
console.log(Object.keys(database))
console.log(Object.getOwnPropertyNames(database))
console.log(Reflect.ownKeys(database))
And they all log:
[ '_container', '_isPublic', '_partition' ]
(EDIT: I also tried using a for
/in
loop, and it also logged the above.)
However, I know this object also has performQuery
and saveRecords
methods, and if I log them specifically I can see them:
console.log(database.performQuery)
// logs [Function: value]
console.log(database.saveRecords);
// logs [Function: value]
Can anyone explain how I can get a list of all of this object's keys, including the "secret" methods?
Upvotes: 2
Views: 56
Reputation: 16886
One of the notorious issues with for/in
in javascript is that it picks up inherited properties. (Thus .hasOwnProperty()
.) So you could do something like this to get all properties, inherited or not:
function(target) {
var results = [];
for(var key in target) {
results.push(key);
}
return results;
}
I learned a lot from your question. Thanks for that.
Here's the code we figured out:
function scanProperties(obj){
var results = [];
while(obj) {
results = results.concat(Object.getOwnPropertyNames(obj));
obj = Object.getPrototypeOf(obj);
}
return results;
}
Basically walks up the inheritance chain, grabbing property names as it goes. Could be improved by eliminating duplicate names when they show up. (Since objects of different "classes" can have some of the same properties, only the "closest" one would apply to the object that we start with.)
Upvotes: 2