0

Is there any way in jQuery to get the name of an object as a string?

i.e. if I have

markers.events = {
    click: function(event){},
    drag: function(event){}
};

I would like to get a string "click" or "drag"

Is this possible inside a $.each(myObj, function(){})?

I need to do the following (hopefully) on the object stated above:

$.each(markers.events, function(i, event){
    google.maps.event.addListener(marker, "click/drag", event);
})
user3708642
  • 124
  • 10
designermonkey
  • 1,078
  • 2
  • 16
  • 28

3 Answers3

1

You could use window["myObj"] , although it only works with Global variables.

tjmehta
  • 28,667
  • 4
  • 21
  • 18
1

The object itself does not have a name. If you do this:

var x = {};

then an object will be created and the variable x will have a reference to it. However, the name of the object is not 'x'. The object is nameless.

You can even declare another variable and set its reference to that same object:

var y = x;

Now both x and y contain a reference to the same (nameless) object.

What you want is stringify the name of a variable, based on its identifier name. That cannot be done.


Update:

The first argument of the $.each callback contains the name of the property:

$.each(markers.event, function(i, v) {
    google.maps.event.addListener(marker, i, v);
});

Live demo: http://jsfiddle.net/simevidas/SKZKv/

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
0

You would do well to explain why you need this so we could help better, but you could do something like this:

var myVars = {
    "myVar1": "Yaay",
    "myVar2": "Yaay again"
};

for(var a in myVars){
    alert("Variable name: "+a);
}
mattsven
  • 22,305
  • 11
  • 68
  • 104