2

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.

3 Answers 3

9

You're looking for Object.keys(obj)

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

Sign up to request clarification or add additional context in comments.

Comments

1

You can try this too.

function  getPropName(obj) {
    var propNameArray= [];
    for (var propertyName in obj) {
      propNameArray.push(propertyName);
      }
    console.log(propNameArray);
  }

2 Comments

the dredges up inherited properties, not just own properties. it's unclear from OP if that's good or bad for his needs...
@dandavis Yes, agreed. If required, we can use hasOwnProperty check.
0

You can try this library on GoogleScriptExamples.com underscoreGS

function checkKeys(){
    var obj = {
     prop1: true,
     prop2: false,
     prop3: false
    };

    var keys = underscoreGS._keys(obj);
    Logger.log(keys);
}

Library project key: MiC3qjLYVUjCCUQpMqPPTWUF7jOZt2NQ8

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.