-3

Say I have this code...

var personA = {
    name: "john"
}

var personB = {
    name: "john"
}

function doSomething(o) {
    alert("Var is: " + o.toString()); // I need to convert 'o' to the object name
}

doSomething(personA);
doSomething(personB);

I want the alert output to be...

Var is: personA
Var is: personB

But I can't figure out how to get the name as string of the object?

MojoDK
  • 4,410
  • 10
  • 42
  • 80
  • 1
    You really want `personA`/`personB` in the output?? The names of the **variables**? Something tells me this is an X/Y problem -- you've asked about Y because you think you need Y to solve problem X, but it's likely that there's a better way to solve problem X than the above. – T.J. Crowder Mar 24 '15 at 12:53
  • dosomething(personA.name.toString()); – AJ_91 Mar 24 '15 at 12:54
  • http://stackoverflow.com/a/22548989/4028085 You can do it like this if you make your "variables" properties of an object... – brso05 Mar 24 '15 at 12:54
  • 3
    Why? What are you trying to solve by getting the variable names? Sounds like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – thefourtheye Mar 24 '15 at 12:54
  • @MojoDK check out my answer I'm not sure if it is what you are looking for but it is an alternative to your problem. – brso05 Mar 24 '15 at 13:00

4 Answers4

2

This is impossible. There is no connection back to the variable.

When you doSomething(personA); you get the value of the variable personA and pass that value to the function.

function doSomething(o) {

The value is copied into o. There is no path back to personA from there.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    Although in this particular case, if you had access to the variables, and only one variable referred to each object, you could figure it out... But this is clearly an X/Y situation. – T.J. Crowder Mar 24 '15 at 12:56
0

Basically no you can't

A hacky way of doing it would be do have

var personA = {
    name: "John",
    variable: "personA"
}

and then just use o.variable

MarshallOfSound
  • 2,629
  • 1
  • 20
  • 26
0
var people = {
    personA: {name: "john"},
    personB: {name: "billy"}
};

for(var variable in people)
{
    alert(variable);
}

Code comes from here

Community
  • 1
  • 1
brso05
  • 13,142
  • 2
  • 21
  • 40
0

You could do something along the lines of

var global = {};
Object.observe(global, function(obj) {
 console.log(obj[0].name);
});
global.personA = { name: "John" };

with EC7 observe

nullpotent
  • 9,162
  • 1
  • 31
  • 42