-2

I'm trying currently to get only the first key of an object for my process. It would allow me to make some comparisons with the root of different objects.

currently I use a loop and break at the first instance. Maybe there is more relevant way to achieve this goal?

var objectKey
var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};


for (var key in p) {
    if (p.hasOwnProperty(key)) {
        var objectKey=key;        
        break
    }
}

 console.log("the first key is: "  + objectKey)

any hint would be great, thanks

Webwoman
  • 5,914
  • 7
  • 26
  • 67

1 Answers1

4

You can use Object.keys():

The Object.keys() method returns an array of a given object's own property names, in the same order as we get with a normal loop.

Then take the key from first index.

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};
var objectKey = Object.keys(p)[0];


 console.log("the first key is: "  + objectKey)
Mamun
  • 58,653
  • 9
  • 33
  • 46