0

From this question Javascript: Reference a variable name from the variable itself the solution to know the name of a variable is to search for the property that stores this name. However, this gives the name of the variable, but not the name of the "original" variable.

Difficult to explain, better with code:

const IndividualValue = (hello) => console.log(Object.keys({hello})[0]);
let theNameOfTheVariable = 'very important info';
IndividualValue(theNameOfTheVariable);

I want

theNameOfTheVariable

but instead I get

hello

Is it possible? Or I need to send the name in a 2nd variable, like

const IndividualValue = (hello, name) => console.log(name);
let theNameOfTheVariable = 'very important info';
IndividualValue(theNameOfTheVariable, 'theNameOfTheVariable');

EDIT: From the duplicate mark, the solution should be:

const IndividualValue = (hello) => console.log(Object.keys(hello)[0]);
let theNameOfTheVariable = 'very important info';
IndividualValue({theNameOfTheVariable});

But, it doesn't work for me. The problem is that the variable is an object, so the following code doesn't work (in my hands, in JSX code):

const IndividualValue = (hello) => console.log(Object.keys(hello)[0]);
let item = {};
item.theNameOfTheVariable = 'very important info';
IndividualValue({item.theNameOfTheVariable}); // syntax error with the dot

https://js.do/code/example000001

GWorking
  • 4,011
  • 10
  • 49
  • 90
  • A value doesn't necessarily have exactly one identifier associated with it. What do you actually need it for? – jonrsharpe Oct 07 '18 at 14:19
  • I need the name to add a "popup" in html that shows the name of the variable, so that I know the name and can locate it easily in the code. Apparently from the "duplicate" label it seems that the solution I've written should work, I'm looking into it – GWorking Oct 07 '18 at 14:23
  • Just use `IndividualValue(item)` in your case to make it work. But really, you always need to explicitly pass the name, there's no other way - just some syntactic sugar to simplify doing that. – Bergi Oct 07 '18 at 17:35

0 Answers0