Home javascript How do I "dereference" a variable's content for use as a variable name?
Reply: 2

javascript How do I "dereference" a variable's content for use as a variable name?

Richard T
Richard T Published in 2018-01-11 18:33:06Z

I want to reduce the I/O overhead of fetching information from the server using XMLHttpRequest() or ActiveXObject(), as appropriate, by making a general-purpose function for doing the fetch which then stores the fetched data using sessionStorage.<variable>. The trouble is, I don't know in advance what the variable names all are, and I intentionally don't want to know.

I was thinking that if there is some way to "dereference" a variable, like we can easily do in BASH, for example, this would be trivial. For example, if the fetched data was in newData, and the name of the file it was fetched from is in dataFile, and if the dereference syntax was, say $(<variableName>), then one could write code like this to store and fetch the data:

//Store the data:
sessionStorage.$(dataFile) = newData;

//Fetch the data:

var storedData = sessionStorage.$(dataFile);

Get it? ... OK, now, how do I ACTUALLY do this?!

...The only other way around this I can see is VERY clumsy - make arrays, one with name, another with values - there MUST be an easier way! TIA.

Jonas W.
Jonas W. Reply to 2018-01-12 06:16:35Z

As always, it is good to visit the docs first. There you can see, that sessionStorage (like localStorage or Map) has no properties at all (except a hidden property pointing to internal memory but thats another thing), but rather makes the data available through its get or set methods:

 sessionStorage.set("a name", "a value");

However the session/localStorage provides also global getters/setters, so in theory one can do:

  sessionStorage.name = "value";

If the keys name is dynamic one could use bracket notation:

   sessionStorage[aName] = aValue;

However, they havent it even mentioned in the docs, so this feature is neither widely supported nor a good coding style.

Hunter Frazier
Hunter Frazier Reply to 2018-01-11 18:57:35Z

Try this. Not exactly sure I followed your question clearly but I would try this if you are having issues using the variable name as string within your other code.

var_param = GET_YOUR_VAR_SOMEHOW; // strip your params as needed
let f1 = { getVarName:var_param.toString()} // object = to f2
let f2 = 'getVarName'; // string = to f1 key

var storedData = sessionStorage.$(f1[f2]); // result of f1[f2] should be your incoming var string, de-referenced from any content.
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.323492 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO