Home > Mobile >  Dynamically create OBJECTS NAME in javascript/jquery, NOT it's keys or values
Dynamically create OBJECTS NAME in javascript/jquery, NOT it's keys or values

Time:12-08

How can you create an object with a dynamically created NAME? NOT dynamically created keys or values. I'd like to learn this in both jQuery and javascript

var com = "thing_"
var bined = "one"
var [com bined] = {}

//so I can populate as such:
thing_one.key = value

I've googled my eyes out and tried a thousand things. Thanks in advance and apologies if I overlooked the obvious.

UPDATE: I accepted BadPiggie answer, as it does function as requested, however, I agree with Teemu and Terry's comments: this is not necessary and doesn't really have a use case.

It was fun to explore, thanks for all your input!

CodePudding user response:

In javascript (In browser) global variables are property of window object. So you can do like this.

var com = "thing_"
var bined = "one"
window[com bined] = {}

//you can populate as such:
thing_one.key = "some value";

console.log(thing_one);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Or you can use eval() but Not Recommended

var com = "thing_"
var bined = "one"
eval(`var ${com   bined} = {}`);

//you can populate as such:
thing_one.key = "some value";

console.log(thing_one);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You need to reference another object to stick your object in. If you did this in a class, you could do this[com bined]={}. Outside of a class, you could do window[com bined]={}.

  • Related