Say I create an object thus:
var myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that:
keys == ["ircEvent", "method", "regex"]
To get all own properties of an object in JavaScript, you can use the Object. getOwnPropertyNames() method. This method returns an array containing all the names of the enumerable and non-enumerable own properties found directly on the object passed in as an argument.
Object properties are defined as a simple association between name and value. All properties have a name and value is one of the attributes linked with the property, which defines the access granted to the property. Properties refer to the collection of values which are associated with the JavaScript 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.
In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:
var keys = Object.keys(myObject);
The above has a full polyfill but a simplified version is:
var getKeys = function(obj){ var keys = []; for(var key in obj){ keys.push(key); } return keys; }
Alternatively replace var getKeys
with Object.prototype.keys
to allow you to call .keys()
on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.
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