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);
})
6
  • 2
    It is not the name of the object. It is the name of the variable. Several variables can have a reference to the same object. Commented Mar 14, 2011 at 19:38
  • 1
    Why don't you ask a question centered around what it is that you're trying to accomplish? Commented Mar 14, 2011 at 19:39
  • What would you need this for? Commented Mar 14, 2011 at 19:39
  • @justkt The question you are referring is not useful. The OP of that question decided to go with object literals instead, so that question is technically unanswered. Commented Mar 14, 2011 at 20:02
  • @Sime - now that the question has been edited there is a significant difference, I agree. It was less obvious before. Commented Mar 14, 2011 at 20:17

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

2 Comments

I've updated the question to be more relevant, can it be done from the new question?
Brilliant! I should have known really. I thought it was an integer iterator, but it's a key isn't it. Thanks v much!
1

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

Comments

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.