Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read name of unknown properties

I have a simple javascript object with several unknown properties containing a value. The problem is that i don't really know the name of the field since it is variable. How can I access this unknown property?

For better understanding I have a simple object like following:

var a = { cat : "meow", dog : "woof"};

I need to read the name and the value of the different properties. I was thinking about something like the following: a.getField(0).name.

like image 700
Kuepper Avatar asked Jul 24 '11 13:07

Kuepper


2 Answers

You can do somethine like this:

for (var member in a) {
    alert('Name: ' + member);
    alert('Value: ' + a[member]);
}

for more info about reflection in JS see here:

http://lpetr.org/blog/archives/reflection-in-javascript

like image 198
Mo Valipour Avatar answered Oct 20 '22 08:10

Mo Valipour


You could access the properties by name:

for (var key in a) {
    var value = a[key];
}

Demo.

like image 24
Darin Dimitrov Avatar answered Oct 20 '22 10:10

Darin Dimitrov