Get the name of a variable (like nameof operator in C#)

dr. rAI picture dr. rAI · May 5, 2016 · Viewed 14.3k times · Source

Let's assume we have the following code:

const myVariable = { age: 7, name: "Hunter" };

I want to know the name of the variable, not just the value of it, and put it in a string or log it or:

const s = nameof(myVariable) + ': ' + JSON.stringify(myVariable);

And the result I want to see is sth like:

"myVariable: {"age":7,"name":"Hunter"}"

Looking forward to see your solution.

Answer

dr. rAI picture dr. rAI · May 5, 2016

This is my own answer in Q&A style which comes with a bit of a compromise. The trick is here to pass the parameter to the function nameof inside an object by enclosing it in curly braces, like this nameof({myVariable}) instead of nameof(myVariable).

Following this convention, the solution can look like this:

var HD = HD || {};
HD.nameof = function (obj) {
  return Object.keys(obj)[0];
}

And this is how I use it to get the name of the variable/object plus the object's content/the variable's value:

const s = HD.nameof({myVariable}) + ': ' + JSON.stringify(myVariable);   

Thus, s will contain the result as requested in the question above.