Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Retrieve key names from an object?

Say I have this:

var x = {  
          a:{a1:"z", a2:"x"},
          b:{b1:"y", b2:"w"}
}

Is there a way to iterate over x to get "a" and "b"?

I want the member name, not its content (I don't want to get {a1:"z", a2:"x"}).

Thanks

like image 815
DanC Avatar asked Sep 21 '10 20:09

DanC


People also ask

What does object keys return in JS?

Object. keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object . The ordering of the properties is the same as that given by looping over the properties of the object manually.

How can you get the list of all properties in an object?

To get all own properties of an object in JavaScript, you can use the Object. getOwnPropertyNames() method. This method returns an array containing all the names of the enumerable and non-enumerable own properties found directly on the object passed in as an argument.


1 Answers

var names = [];
for(var key in x) {
   if(x.hasOwnProperty(key)) {
      names.push(key);
   }
}
alert(names.join(', ')); //a, b
like image 68
Jacob Relkin Avatar answered Oct 08 '22 13:10

Jacob Relkin