Reputation: 3
Simple issue I ran up against today and can't seem to find a way around it, whatever the solution is it's something I've never learned so leaving me stumped.
For reasons I won't get into, I need to get a value from an object and use it as the name of a new variable. Will be looping through a ton of these so needs to be repeatable. For example from an object like so,
obj = {
"name": "object101"
};
What I want to get out of that is a var declaration in such a way that object101 is the name of the new var,
"var object101 = // stuff"
But "var obj.name = // stuff"
is not working, the dot is not valid it seems.
I also tried putting the object101 into it's own var like, var name = obj.name;
.
Which holds the content fine. But then I immediately saw the hilarious problem with going, var name = // stuff
It just redefines "name" and is not placing the content of name. It does render right when in a console log like console.log("var "+name+" = stuff");
which is pretty much exactly how I want it to write to the code, but having this issue in the real code with the var being redefined in this case.
So I feel like I am missing something very basic in how you can provide the name to declare a var. Maybe some very simple syntax thing I am missing, or perhaps there is a process out there which will dynamically make a var declaration name based on some other object. I've done my fair share of js and never seen var [complex syntax resulting in name] =
, it's always quite simple.
But my searching has drawn a blank so far on this exact issue. Anyone able to enlighten me?
Upvotes: 0
Views: 144
Reputation: 44386
Wow, you really don't want to do what you think you want to do, but here goes.
If you are operating in a browser and you want the variables to be in global scope, fortunately the global scope has a name: window
.
You can just do this:
window[obj.name] = 'stuff';
If you want it in in local scope, you can use the almost-forbidden keyword with
:
var f = function(obj, b) {
var fake_scope = {};
with (fake_scope) {
fake_scope[obj.name] = b;
console.log(d);
}
}
f( { name : 'd' } , 3 )
will print out 3.
If you need local scope and you don't want to use with
, you will have to screw around with eval
.
But seriously, if you do this, remember.
Upvotes: 2
Reputation: 8192
Well, in the interest of science:
(function() {
var dynaVarName = 'testName';
eval('var ' + dynaVarName + ';');
eval(dynaVarName + ' = 5;');
eval('console.log(' + dynaVarName + ');'); // => 5
}());
testName // => ReferenceError
So yes, you actually can create a local variable with a name based on an expression. I can't imagine the benefits of doing this though.
Upvotes: 1