Related
Is there a way to get a variable name as a string in Javascript? (like NSStringFromSelector in Cocoa)
I would like to do like this:
var myFirstName = 'John';
alert(variablesName(myFirstName) + ":" + myFirstName);
--> myFirstName:John
UPDATE
I'm trying to connect a browser and another program using JavaScript. I would like to send instance names from a browser to another program for callback method:
FooClass = function(){};
FooClass.someMethod = function(json) {
// Do something
}
instanceA = new FooClass();
instanceB = new FooClass();
doSomethingInAnotherProcess(instanceB); // result will be substituted by using instanceB.someMethod();
...
From another program:
evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");
In PHP:
How to get a variable name as a string in PHP?
Like Seth's answer, but uses Object.keys() instead:
const varToString = varObj => Object.keys(varObj)[0]
const someVar = 42
const displayName = varToString({ someVar })
console.log(displayName)
You can use the following solution to solve your problem:
const myFirstName = 'John'
Object.keys({myFirstName})[0]
// returns "myFirstName"
Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.
var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
console.log(key + ': ' + obj[key]);
In ES6, you could write something like:
let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
for(let varName in nameObject) {
return varName;
}
}
let varName = getVarNameFromObject(nameObject);
console.log(varName);
Not really the best looking thing, but it gets the job done.
This leverages ES6's object destructuring.
More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
Get a string from any valid Javascript (variable, class):
const nameOf = (f) => (f).toString().replace(/[ |\(\)=>]/g,'');
Examples:
nameOf(() => myVariable) // myVariable
nameOf(() => myVariable.name) // myVariable.name
nameOf(() => myVariable.name.length) // myVariable.name.length
nameOf(() => myVariable.name[10]) // myVariable.name[10]
nameOf(() => MySuperClass) // MySuperClass
Probably pop would be better than indexing with [0], for safety (variable might be null).
const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${myFirstName}'`);
// returns "Variable myFirstName with value 'John'"
var x = 2;
for(o in window){
if(window[o] === x){
alert(o);
}
}
However, I think you should do like "karim79"
This works for basic expressions
const nameof = exp => exp.toString().match(/[.](\w+)/)[1];
Example
nameof(() => options.displaySize);
Snippet:
var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };
var myFirstName = 'Chuck';
var varname = nameof(function () { return window.myFirstName; });
console.log(varname);
var somefancyvariable = "fancy";
Object.keys({somefancyvariable})[0];
This isn't able to be made into a function as it returns the name of the function's variable.
// THIS DOESN'T WORK
function getVarName(v) {
return Object.keys({v})[0];
}
// Returns "v"
Edit: Thanks to #Madeo for pointing out how to make this into a function.
function debugVar(varObj) {
var varName = Object.keys(varObj)[0];
console.log("Var \"" + varName + "\" has a value of \"" + varObj[varName] + "\"");
}
You will need call the function with a single element array containing the variable. debugVar({somefancyvariable});
Edit: Object.keys can be referenced as just keys in every browser I tested it in but according to the comments it doesn't work everywhere.
Shortest way I have found so far to get the variables name as a string:
const name = obj => Object.keys(obj)[0];
const whatsMyName = "Snoop Doggy Dogg";
console.log( "Variable name is: " + name({ whatsMyName }) );
//result: Variable name is: whatsMyName
Since ECMAScript 5.1 you can use Object.keys to get the names of all properties from an object.
Here is an example:
// Get John’s properties (firstName, lastName)
var john = {firstName: 'John', lastName: 'Doe'};
var properties = Object.keys(john);
// Show John’s properties
var message = 'John’s properties are: ' + properties.join(', ');
document.write(message);
best way using Object.keys();
example : for getting multi variables names in global scope
// multi variables for testing
var x = 5 , b = true , m = 6 , v = "str";
// pass all variables you want in object
function getVarsNames(v = {}){
// getting keys or names !
let names = Object.keys(v);
// return array contain all names of variables
return names;
}
// testing if that work or not
let VarsNames = getVarsNames({x , b , m , v});
console.log(VarsNames); // output is array [x , b , m , v]
This worked using Internet Explorer (9, 10 and 11), Google Chrome 5:
var myFirstName = "Danilo";
var varName = Object.keys({myFirstName:0})[0];
console.log(varName);
Browser compatibility table:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
For those who would like to print variableName and variableValue for debugging purposes, here is a function:
const printNameValue = (v)=> {
var varName = (v).toString().replace(/[ |\(\)=>]/g, '')
var varValue = (v)()
// neat : console.log(varName,varValue);
// with some coloring :
console.log("\033[1;96m[\033[1;33m " + varName + " :\033[0;0m " + varValue+"\033[1;96m ]\033[0;0m");
}
Example:
const myNiceVariable = 1234
call:
printNameValue(()=> myNiceVariable )
result:
You can reflect on types in javascript and get the name of properties and methods but what you need is sth like Lambda Expressions Trees in .NET, I think it's not be possible due to dynamic nature and lack of static type system in javascript.
I needed this, don't want to use objects, and came up with the following solution, turning the question around.
Instead of converting the variable name into a string, I convert a string into a variable.
This only works if the variable name is known of course.
Take this:
var height = 120;
testAlert(height);
This should display:
height: 120
This can be done like this:
function testAlert(ta)
{
a = window[ta];
alert(ta + ': ' + a);
}
var height = 120;
testAlert("height");
// displays: height: 120
So I use the string "height" and turn that into a variable height using the window[] command.
When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.
Run in jsfiddle
var jack = 'jill';
function window_getVarName(what)
{
for (var name in window)
{
if (window[name]==what)
return(name);
}
return("");
}
document.write(window_getVarName(jack));
Will write to the window 'jack'.
I've created this function based on JSON as someone suggested, works fine for my debug needs
function debugVar(varNames){
let strX = "";
function replacer(key, value){
if (value === undefined){return "undef"}
return value
}
for (let arg of arguments){
let lastChar;
if (typeof arg!== "string"){
let _arg = JSON.stringify(arg, replacer);
_arg = _arg.replace('{',"");
_arg = _arg.replace('}',"");
_arg = _arg.replace(/:/g,"=");
_arg = _arg.replace(/"/g,"");
strX+=_arg;
}else{
strX+=arg;
lastChar = arg[arg.length-1];
}
if (arg!==arguments[arguments.length-1]&&lastChar!==":"){strX+=" "};
}
console.log(strX)
}
let a = 42, b = 3, c;
debugVar("Begin:",{a,b,c},"end")
If you're looking for something quick and dirty, this might work:
var zox = 150;
cl("zox");
function cl(c) {
console.log(c + ': ' + this[c]); // zox: 150
}
No, there is not.
Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").
Is there a way to get a variable name as a string in Javascript? (like NSStringFromSelector in Cocoa)
I would like to do like this:
var myFirstName = 'John';
alert(variablesName(myFirstName) + ":" + myFirstName);
--> myFirstName:John
UPDATE
I'm trying to connect a browser and another program using JavaScript. I would like to send instance names from a browser to another program for callback method:
FooClass = function(){};
FooClass.someMethod = function(json) {
// Do something
}
instanceA = new FooClass();
instanceB = new FooClass();
doSomethingInAnotherProcess(instanceB); // result will be substituted by using instanceB.someMethod();
...
From another program:
evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");
In PHP:
How to get a variable name as a string in PHP?
Like Seth's answer, but uses Object.keys() instead:
const varToString = varObj => Object.keys(varObj)[0]
const someVar = 42
const displayName = varToString({ someVar })
console.log(displayName)
You can use the following solution to solve your problem:
const myFirstName = 'John'
Object.keys({myFirstName})[0]
// returns "myFirstName"
Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.
var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
console.log(key + ': ' + obj[key]);
In ES6, you could write something like:
let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
for(let varName in nameObject) {
return varName;
}
}
let varName = getVarNameFromObject(nameObject);
console.log(varName);
Not really the best looking thing, but it gets the job done.
This leverages ES6's object destructuring.
More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
Get a string from any valid Javascript (variable, class):
const nameOf = (f) => (f).toString().replace(/[ |\(\)=>]/g,'');
Examples:
nameOf(() => myVariable) // myVariable
nameOf(() => myVariable.name) // myVariable.name
nameOf(() => myVariable.name.length) // myVariable.name.length
nameOf(() => myVariable.name[10]) // myVariable.name[10]
nameOf(() => MySuperClass) // MySuperClass
Probably pop would be better than indexing with [0], for safety (variable might be null).
const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${myFirstName}'`);
// returns "Variable myFirstName with value 'John'"
var x = 2;
for(o in window){
if(window[o] === x){
alert(o);
}
}
However, I think you should do like "karim79"
This works for basic expressions
const nameof = exp => exp.toString().match(/[.](\w+)/)[1];
Example
nameof(() => options.displaySize);
Snippet:
var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };
var myFirstName = 'Chuck';
var varname = nameof(function () { return window.myFirstName; });
console.log(varname);
var somefancyvariable = "fancy";
Object.keys({somefancyvariable})[0];
This isn't able to be made into a function as it returns the name of the function's variable.
// THIS DOESN'T WORK
function getVarName(v) {
return Object.keys({v})[0];
}
// Returns "v"
Edit: Thanks to #Madeo for pointing out how to make this into a function.
function debugVar(varObj) {
var varName = Object.keys(varObj)[0];
console.log("Var \"" + varName + "\" has a value of \"" + varObj[varName] + "\"");
}
You will need call the function with a single element array containing the variable. debugVar({somefancyvariable});
Edit: Object.keys can be referenced as just keys in every browser I tested it in but according to the comments it doesn't work everywhere.
Shortest way I have found so far to get the variables name as a string:
const name = obj => Object.keys(obj)[0];
const whatsMyName = "Snoop Doggy Dogg";
console.log( "Variable name is: " + name({ whatsMyName }) );
//result: Variable name is: whatsMyName
Since ECMAScript 5.1 you can use Object.keys to get the names of all properties from an object.
Here is an example:
// Get John’s properties (firstName, lastName)
var john = {firstName: 'John', lastName: 'Doe'};
var properties = Object.keys(john);
// Show John’s properties
var message = 'John’s properties are: ' + properties.join(', ');
document.write(message);
best way using Object.keys();
example : for getting multi variables names in global scope
// multi variables for testing
var x = 5 , b = true , m = 6 , v = "str";
// pass all variables you want in object
function getVarsNames(v = {}){
// getting keys or names !
let names = Object.keys(v);
// return array contain all names of variables
return names;
}
// testing if that work or not
let VarsNames = getVarsNames({x , b , m , v});
console.log(VarsNames); // output is array [x , b , m , v]
This worked using Internet Explorer (9, 10 and 11), Google Chrome 5:
var myFirstName = "Danilo";
var varName = Object.keys({myFirstName:0})[0];
console.log(varName);
Browser compatibility table:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
For those who would like to print variableName and variableValue for debugging purposes, here is a function:
const printNameValue = (v)=> {
var varName = (v).toString().replace(/[ |\(\)=>]/g, '')
var varValue = (v)()
// neat : console.log(varName,varValue);
// with some coloring :
console.log("\033[1;96m[\033[1;33m " + varName + " :\033[0;0m " + varValue+"\033[1;96m ]\033[0;0m");
}
Example:
const myNiceVariable = 1234
call:
printNameValue(()=> myNiceVariable )
result:
You can reflect on types in javascript and get the name of properties and methods but what you need is sth like Lambda Expressions Trees in .NET, I think it's not be possible due to dynamic nature and lack of static type system in javascript.
I needed this, don't want to use objects, and came up with the following solution, turning the question around.
Instead of converting the variable name into a string, I convert a string into a variable.
This only works if the variable name is known of course.
Take this:
var height = 120;
testAlert(height);
This should display:
height: 120
This can be done like this:
function testAlert(ta)
{
a = window[ta];
alert(ta + ': ' + a);
}
var height = 120;
testAlert("height");
// displays: height: 120
So I use the string "height" and turn that into a variable height using the window[] command.
When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.
Run in jsfiddle
var jack = 'jill';
function window_getVarName(what)
{
for (var name in window)
{
if (window[name]==what)
return(name);
}
return("");
}
document.write(window_getVarName(jack));
Will write to the window 'jack'.
I've created this function based on JSON as someone suggested, works fine for my debug needs
function debugVar(varNames){
let strX = "";
function replacer(key, value){
if (value === undefined){return "undef"}
return value
}
for (let arg of arguments){
let lastChar;
if (typeof arg!== "string"){
let _arg = JSON.stringify(arg, replacer);
_arg = _arg.replace('{',"");
_arg = _arg.replace('}',"");
_arg = _arg.replace(/:/g,"=");
_arg = _arg.replace(/"/g,"");
strX+=_arg;
}else{
strX+=arg;
lastChar = arg[arg.length-1];
}
if (arg!==arguments[arguments.length-1]&&lastChar!==":"){strX+=" "};
}
console.log(strX)
}
let a = 42, b = 3, c;
debugVar("Begin:",{a,b,c},"end")
If you're looking for something quick and dirty, this might work:
var zox = 150;
cl("zox");
function cl(c) {
console.log(c + ': ' + this[c]); // zox: 150
}
No, there is not.
Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").
Is there a way to get a variable name as a string in Javascript? (like NSStringFromSelector in Cocoa)
I would like to do like this:
var myFirstName = 'John';
alert(variablesName(myFirstName) + ":" + myFirstName);
--> myFirstName:John
UPDATE
I'm trying to connect a browser and another program using JavaScript. I would like to send instance names from a browser to another program for callback method:
FooClass = function(){};
FooClass.someMethod = function(json) {
// Do something
}
instanceA = new FooClass();
instanceB = new FooClass();
doSomethingInAnotherProcess(instanceB); // result will be substituted by using instanceB.someMethod();
...
From another program:
evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");
In PHP:
How to get a variable name as a string in PHP?
Like Seth's answer, but uses Object.keys() instead:
const varToString = varObj => Object.keys(varObj)[0]
const someVar = 42
const displayName = varToString({ someVar })
console.log(displayName)
You can use the following solution to solve your problem:
const myFirstName = 'John'
Object.keys({myFirstName})[0]
// returns "myFirstName"
Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.
var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
console.log(key + ': ' + obj[key]);
In ES6, you could write something like:
let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
for(let varName in nameObject) {
return varName;
}
}
let varName = getVarNameFromObject(nameObject);
console.log(varName);
Not really the best looking thing, but it gets the job done.
This leverages ES6's object destructuring.
More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
Get a string from any valid Javascript (variable, class):
const nameOf = (f) => (f).toString().replace(/[ |\(\)=>]/g,'');
Examples:
nameOf(() => myVariable) // myVariable
nameOf(() => myVariable.name) // myVariable.name
nameOf(() => myVariable.name.length) // myVariable.name.length
nameOf(() => myVariable.name[10]) // myVariable.name[10]
nameOf(() => MySuperClass) // MySuperClass
Probably pop would be better than indexing with [0], for safety (variable might be null).
const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${myFirstName}'`);
// returns "Variable myFirstName with value 'John'"
var x = 2;
for(o in window){
if(window[o] === x){
alert(o);
}
}
However, I think you should do like "karim79"
This works for basic expressions
const nameof = exp => exp.toString().match(/[.](\w+)/)[1];
Example
nameof(() => options.displaySize);
Snippet:
var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };
var myFirstName = 'Chuck';
var varname = nameof(function () { return window.myFirstName; });
console.log(varname);
var somefancyvariable = "fancy";
Object.keys({somefancyvariable})[0];
This isn't able to be made into a function as it returns the name of the function's variable.
// THIS DOESN'T WORK
function getVarName(v) {
return Object.keys({v})[0];
}
// Returns "v"
Edit: Thanks to #Madeo for pointing out how to make this into a function.
function debugVar(varObj) {
var varName = Object.keys(varObj)[0];
console.log("Var \"" + varName + "\" has a value of \"" + varObj[varName] + "\"");
}
You will need call the function with a single element array containing the variable. debugVar({somefancyvariable});
Edit: Object.keys can be referenced as just keys in every browser I tested it in but according to the comments it doesn't work everywhere.
Shortest way I have found so far to get the variables name as a string:
const name = obj => Object.keys(obj)[0];
const whatsMyName = "Snoop Doggy Dogg";
console.log( "Variable name is: " + name({ whatsMyName }) );
//result: Variable name is: whatsMyName
Since ECMAScript 5.1 you can use Object.keys to get the names of all properties from an object.
Here is an example:
// Get John’s properties (firstName, lastName)
var john = {firstName: 'John', lastName: 'Doe'};
var properties = Object.keys(john);
// Show John’s properties
var message = 'John’s properties are: ' + properties.join(', ');
document.write(message);
best way using Object.keys();
example : for getting multi variables names in global scope
// multi variables for testing
var x = 5 , b = true , m = 6 , v = "str";
// pass all variables you want in object
function getVarsNames(v = {}){
// getting keys or names !
let names = Object.keys(v);
// return array contain all names of variables
return names;
}
// testing if that work or not
let VarsNames = getVarsNames({x , b , m , v});
console.log(VarsNames); // output is array [x , b , m , v]
This worked using Internet Explorer (9, 10 and 11), Google Chrome 5:
var myFirstName = "Danilo";
var varName = Object.keys({myFirstName:0})[0];
console.log(varName);
Browser compatibility table:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
For those who would like to print variableName and variableValue for debugging purposes, here is a function:
const printNameValue = (v)=> {
var varName = (v).toString().replace(/[ |\(\)=>]/g, '')
var varValue = (v)()
// neat : console.log(varName,varValue);
// with some coloring :
console.log("\033[1;96m[\033[1;33m " + varName + " :\033[0;0m " + varValue+"\033[1;96m ]\033[0;0m");
}
Example:
const myNiceVariable = 1234
call:
printNameValue(()=> myNiceVariable )
result:
You can reflect on types in javascript and get the name of properties and methods but what you need is sth like Lambda Expressions Trees in .NET, I think it's not be possible due to dynamic nature and lack of static type system in javascript.
I needed this, don't want to use objects, and came up with the following solution, turning the question around.
Instead of converting the variable name into a string, I convert a string into a variable.
This only works if the variable name is known of course.
Take this:
var height = 120;
testAlert(height);
This should display:
height: 120
This can be done like this:
function testAlert(ta)
{
a = window[ta];
alert(ta + ': ' + a);
}
var height = 120;
testAlert("height");
// displays: height: 120
So I use the string "height" and turn that into a variable height using the window[] command.
When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.
Run in jsfiddle
var jack = 'jill';
function window_getVarName(what)
{
for (var name in window)
{
if (window[name]==what)
return(name);
}
return("");
}
document.write(window_getVarName(jack));
Will write to the window 'jack'.
I've created this function based on JSON as someone suggested, works fine for my debug needs
function debugVar(varNames){
let strX = "";
function replacer(key, value){
if (value === undefined){return "undef"}
return value
}
for (let arg of arguments){
let lastChar;
if (typeof arg!== "string"){
let _arg = JSON.stringify(arg, replacer);
_arg = _arg.replace('{',"");
_arg = _arg.replace('}',"");
_arg = _arg.replace(/:/g,"=");
_arg = _arg.replace(/"/g,"");
strX+=_arg;
}else{
strX+=arg;
lastChar = arg[arg.length-1];
}
if (arg!==arguments[arguments.length-1]&&lastChar!==":"){strX+=" "};
}
console.log(strX)
}
let a = 42, b = 3, c;
debugVar("Begin:",{a,b,c},"end")
If you're looking for something quick and dirty, this might work:
var zox = 150;
cl("zox");
function cl(c) {
console.log(c + ': ' + this[c]); // zox: 150
}
No, there is not.
Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 3 years ago.
I am trying to use a variable when declaring an object:
var name1 = "object1";
var data1 = 3;
create_object(name1, data1);
function create_object(name, data) {
var x = {
name: data
}
return x
}
I want x to be stored as
var x = {
object1: 3
}
But my function will make
var x = {
name: 3
}
Is there a way to pass a variable when declaring the name of a child inside an object?
Thanks a lot
To specify a name of a property from a variable you need to use the square brackets notation like this:
function create_object(name, data) {
var x = {};
x[name] = data;
return x;
}
Is it possible to print / display a JavaScript variable's name? For example:
var foo=5;
var bar=6;
var foobar=foo+bar;
document.write(foo+ "<br>");
document.write(bar+ "<br>");
document.write(foobar + "<br>");
How would we print the variable's names so the output would be:
foo
bar
foobar
Rather than:
5
6
11
You can put the variables in an object then easily print them this way: http://jsfiddle.net/5MVde/7/
See fiddle for everything, this is the JavaScript...
var x = {
foo: 5,
bar: 6,
foobar: function (){
var that=this;
return that.foo+that.bar
}
};
var myDiv = document.getElementById("results");
myDiv.innerHTML='Variable Names...';
for(var variable in x)
{
//alert(variable);
myDiv.innerHTML+='<br>'+variable;
}
myDiv.innerHTML+='<br><br>And their values...';
myDiv.innerHTML+='<br>'+x.foo+'<br>'+x.bar+'<br>'+x.foobar();
The JavaScript for...in statement loops through the properties of an object.
Another variation (thanks #elclanrs) if you don't want foobar to be a function: http://jsfiddle.net/fQ5hE/2/
Utils = {
eventRegister_globalVariable : function(variableName,handlers){
eventRegister_JsonVariable(this,variableName,handlers);
},
eventRegister_jsonVariable : function(jsonObj,variableName,handlers){
if(jsonObj.eventRegisteredVariable === undefined) {
jsonObj.eventRegisteredVariable={};//this Object is used for trigger event in javascript variable value changes ku
}
Object.defineProperty(jsonObj, variableName , {
get: function() {
return jsonObj.eventRegisteredVariable[variableName] },
set: function(value) {
jsonObj.eventRegisteredVariable[variableName] = value; handlers(jsonObj.eventRegisteredVariable[variableName]);}
});
}
Another possible solution can be "Object.keys(this)".... This will give you all the variable names in an array.