How to get all properties of an object using reflection in JavaScript?
getOwnPropertyNames() The Object. getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.
values() Method: The Object. values() method is used to return an array of the object's own enumerable property values. The array can be looped using a for-loop to get all the values of the object.
First way to print all properties of person object is by using Object. keys() method. In this method we pass the person object to Object. keys() as an argument.
Loop through the object and take every key that belongs to it and is not a function:
var properties = []; for(var key in obj) { if(obj.hasOwnProperty(key) && typeof obj[key] !== 'function') { properties.push(key); } }
In modern browsers, to get all property names (not just enumerable properties), you'd use Object.getOwnPropertyNames
...
var props = Object.getOwnPropertyNames(my_object)
If you don't want enumerable properties, you'd use Object.keys
...
var props = Object.keys(my_object)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With