Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an object property name as string

Is it possible to get the property names of an object as an array of strings?

For example if I made the object:

var obj = {
 prop1: true,
 prop2: false,
 prop3: false
}

s there a some method 'getPropNames(obj)' that would return an array where each element is a property name so it would look like this:

props[0] = "prop1" 
props[1] = "prop2" 
props[2] = "prop3" 

Thanks in advance for any help.

like image 513
Tim Avatar asked Dec 04 '25 03:12

Tim


2 Answers

You're looking for Object.keys(obj)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

like image 123
Abraham P Avatar answered Dec 06 '25 16:12

Abraham P


You can try this too.

function  getPropName(obj) {
    var propNameArray= [];
    for (var propertyName in obj) {
      propNameArray.push(propertyName);
      }
    console.log(propNameArray);
  }
like image 24
Harry Avatar answered Dec 06 '25 18:12

Harry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!