JavaScript - List the properties of an object

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
PloMar
Posts: 48

JavaScript - List the properties of an object

I have an object like this in javascript:

Code: Select all

var obj = {
  prop1: 'val 1',
  prop2: 'val 2',
  prop3: 'val 3'
};
What is the best way to retrieve a list of the property names?
I would like to end up with some variable 'props' such that:

Code: Select all

props == ['prop1', 'prop2', 'prop3']

Admin
You can use the built in Object.keys method:

Code: Select all

var obj = {
  prop1: 'val 1',
  prop2: 'val 2',
  prop3: 'val 3'
};

var props = Object.keys(obj);

console.log(props);  // ['prop1', 'prop2', 'prop3']

Similar Topics