-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?

5
  • 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. Commented Mar 24, 2015 at 12:53
  • dosomething(personA.name.toString()); Commented Mar 24, 2015 at 12:54
  • stackoverflow.com/a/22548989/4028085 You can do it like this if you make your "variables" properties of an object... Commented Mar 24, 2015 at 12:54
  • 3
    Why? What are you trying to solve by getting the variable names? Sounds like an XY problem Commented Mar 24, 2015 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. Commented Mar 24, 2015 at 13:00

4 Answers 4

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.

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

1 Comment

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.
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

Comments

0
var people = {
    personA: {name: "john"},
    personB: {name: "billy"}
};

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

Code comes from here

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.