Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list the properties of a JavaScript object?

Tags:

javascript

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"] 
like image 601
johnstok Avatar asked Oct 16 '08 10:10

johnstok


People also ask

How do you list all properties of an object in JS?

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.

What are the properties of an object in JavaScript?

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.

How do I print all properties of an 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.


1 Answers

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.

like image 135
slashnick Avatar answered Oct 03 '22 01:10

slashnick