Convert String name into javascript variable name? [duplicate] - javascript

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 8 years ago.
Problem with example:
Variable name: var product5519 = 10;
I can get this name in the form of a String i.e
var str = "product5519"
Is there any way to convert it into variable name so that i can use the value assigned to
product5519
I know one way to solve this problem i.e using eval(str)
If there is any another way to solve it please tell?

Once you are certain creating a global variable was the Right Thing to do, you can add your variable to the window object, like so:
window[str] = 42;
This works because variable lookups end up trying the window object if the variable was not defined in an inner scope.

It's a bit hacky but if you wanted to make a global variable you could do:
var str = "product5519";
window[str] = value;
You could then access the variable like:
window[str];
window.str;
str; // Assuming that there is no local variable already named "str"

you could do something like:
window['product5519'] = 'value'
it may be better to have an array of products, depending on the situation ofc.

You can use an associative array:
var variables = [];
variables['product5519'] = 10;
console.log(variables['product5519']);

Related

Angular: Change String to variable [duplicate]

This question already has answers here:
Convert string to variable name in JavaScript
(11 answers)
Closed 6 years ago.
Apologies if this is simple. I just couldn't figure-out how to do it. Searched on this site on how to dynamically change variables and evaluate them etc but can't figure out how to do what I want.
Problem: I have a variable that I set to a value:
vm.toggleDrop = function($switchToggle){
vm.switchValue = "switch"+$switchToggle;
//Here
};
Where it says "Here", I need to instantiate a new variable that is called whatever is the result if the above statement eg; switch1 then set it true or false as a boolean. eg: switch1 = false;
Therefore again, if $switchToggle parameter was "Test", I need to dynamically create a variable called switchTest and set it true or false.
Is such a thing possible ?
Thanks all
Something like that?(I created vm variable just for code snippet, ignore it)
var vm = {};
vm.toggleDrop = function($switchToggle){
vm.switchValue = "switch"+$switchToggle;
vm[vm.switchValue] = 'whatever';
console.log(vm);
};
vm.toggleDrop('true');
Also if you do not need to attach variable to vm object, best answer will be #nastyklad provided(using window[vm.switchValue]
Something like this:
function setVariable(name){
var variableName = 'switch' + name;
vm[variableName] = true;
}

Create variable name based on argument sent to function in javascript [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 7 years ago.
I wanted to create variable name based on value sent to function in javascript.
like following, when i call function variable : variable("zebra"); this should return variable name as zebra1
function create variable(i){
return i+"1";
}
var variable("zebra")="abc";//this line should create variable zebra1 and initialise as abc
Try:
window['zebra'] = 'abc';
The window object holds all the global variables, assuming this is a request for global variables.
To specifically answer your question, you could put return window[i + '1'] = 'abc'; in your variable naming function.
Alternatively, you could create a global (or local) object named variables to hold all your variables:
function whoknows() {
var variables = {};
variables['zebra'] = 'abc';
}
Read more on working with objects at mozilla.org
You can create global variable with
window["zebra"] = "abc";
and use later ether with the same indexer syntax or directly - zebra.

Using String to get JSON Property [duplicate]

This question already has an answer here:
Accessing a JSON property (String) using a variable
(1 answer)
Closed 8 years ago.
I want to use a string as a JSON property in JavaScript.
var knights = {
'phrases': 'Ni!'
};
var x = 'phrases';
console.log(knights.x); // Doesn't log "Ni!"
When I run this code, it obviously doesn't work because it interprets "x" and not the contents of the variable "x".
The full code in context on pastebin: http://pastebin.com/bMQJ9EDf
Is there an easy solution to this?
knights.x looks for a property named x. You want knights[x], which is equivalent to knights['phrases'] == knights.phrases.
Full code (fixing a couple of typos in your example):
var knights = {
"phrases": "Ni!"
};
var x = 'phrases';
console.log(knights[x]); // logs Ni!
Try this to access using variables having string values
kinghts[x]
Basically this is trick
kinghts[x]==knighted["phrases"]==knighted.phrases.
knights.x will get a key named x, So it'll return undefined here.
knights.x is the same as knights['x'] - retrieving a property under the key x. It's not accessing the variable x and substituting in the value. Instead, you want knights[x] which is the equivalent of knights['phrases']

How to turn variable name into string in JS? [duplicate]

This question already has answers here:
Variable name as a string in Javascript
(20 answers)
Closed 2 years ago.
I am trying to write a convenience wrapper for console.log, and I would like to print any variables passed in along with their contents.
Can I turn a variable name into a string in js?
Assuming you want something like this:
function Log(data)
{
console.log(input variable name, data);
}
Then I don't think it is possible:
For convenience.. you could do something like
console.log({ "your variable name": your variable});
Which turns the input to an object that does contain the variable name you want to log.
A little more typing, but perhaps makes the console output more readable.
There is a possibility. And here is how
var passed_variable = '65'; // The actual variable
var varname = 'passed_variable'; // The name of the variable in another variable
Now, pass the varname around but not the actual variable. When you need to the value of the variable you can simply do :
console.log(varname, ' : ', window[varname]); // Outputs, passed_variable : 65
I hope you find a way not to use this. :)

Setting and using dynamic variable name JS [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 9 years ago.
I can't figure out how to use the name of a variable previously created with eval, without knowing it.
I mean:
function getName(menu_name, level){
eval("var menu_"+level+"="+menu_name);
}
Now how do I get the name of the variable I just created? Probably keep using eval, but I have to put that name into a $.post call as one of my field name.
Thanks in advice.
If level is an integer, you can treat it as a numerical index for an array:
var menu = [];
menu[level] = menu_name;
If level is anything else, you can treat it as a key for a dictionary/associative array:
var menu = {};
menu[level] = menu_name;
Then, for either of the solutions, if you want to access your menu_name, simply call menu[level].

Categories