Page 1 of 1

JavaScript - List the properties of an object

Posted: 14 Jan 2015, 09:10
by PloMar
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']

JavaScript - List the properties of an object

Posted: 14 Jan 2015, 09:12
by 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']