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
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.
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.
var names = [];
for(var key in x) {
if(x.hasOwnProperty(key)) {
names.push(key);
}
}
alert(names.join(', ')); //a, b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With