javascript use var value as name for new var - javascript

How can I use an array key (text value) to reference a variable by that same name?
jsFiddle
var cr,au,gen,bn,fmt,str;
var sbASCtrls = {"cr":"ContentRating","au":"Gold","gen":"Gender","bn":"Big Number","fmt":"Format","str":"Starting String"};
for (var key in sbASCtrls){
//This does not work ... breaks script
"'"+key+"'" = sbASCtrls[key];
alert('var CR: ' + cr);
return false;
}
In another language, I would simply surround the var name with percent signs, thus:
var %key% = "bob";
Would make:
var cr = bob;
How can this be done in javascript?
Why I require this unusual solution:
A series of AJAX calls are being made to a pre-existing PHP processor file that expects all data in HTML. In this case, I already had the data in JSON/jsObj format and wished to quickly break it out into separate variables. The most efficient/readable (believe it or not!) code was achieved by using eval(). After reading Jonathan's and Niet's posts/comments, I struggled with how to keep the data in JSON format and use it like that, but the AJAX processor always requires one piece of data in HTML format. To my disappointment, I was unable to find a way to mix the two data types. Faced with the choice of re-coding the entire app to use JSON only, or moving ahead with HTML, the SDLC made the decision for me.
Thanks Niet, Jonathan, Cristy, Stephen Thomas and Fallenreaper for sound advice and great ideas. I'll be scoping other posts you've each made.

While you could use eval like this:
// DO NOT DO THIS
eval(key+" = svASCtrls[key];");
You should probably stop and ask yourself why you want to do this in the first place. You already have a very tidy object, so just use it...

You can define your variables as properties of an object
var obj = { cr: null, au: null, gen: null, bn: null, fmt: null, str: null };
var sbASCtrls = {"cr":"ContentRating","au":"Gold","gen":"Gender","bn":"Big Number","fmt":"Format","str":"Starting String"};
for (var key in sbASCtrls){
//This does not work ... breaks script
obj[key] = sbASCtrls[key];
alert('var CR: ' + obj.cr);
return false;
}

As any global variable is a child of the window object, you can create the variable at window[key]
for (var key in sbASCtrls){
alert("key: " + key);
alert("val: " + sbASCtrls[key] );
//This should work, but jsfiddle messes with the window object
window[key] = sbASCtrls[key];
alert('var CR: ' + cr);
return false;
}
Note that this does not work on jsfiddle, but should work on your website.

Related

Having trouble referring to object within array

I am trying to write an html page for class that uses a drop down menu to allow users to pull up a list of relevant information. Unfortunately I am having trouble figuring out how to make the script call on the information in the array. The jsfiddle has the full html section, any help would be GREATLY appreciated.
Please bear in mind that I am not very good with terminology, so be as specific as possible. Especially regarding jQuery, our teacher didn't go over it much so it's a freaking mystery to me.
Also, I do plan on adding more information to the objects in the array, but until I get it working, I don't want to waste the time on something I might need to restructure.
http://jsfiddle.net/GamerGorman20/nw8Ln6ha/11/
var favWebComics = [
Goblins = {1: "www.goblinscomic.org"},
GirlGenious = {1: "www.girlgeniousonline.com"},
GrrlPower = {1: "www.grrlpowercomic.com"}
];
var myFunction = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
document.getElementById("web").innerHTML = favWebComics.x;
};
Again, the JSFiddle link has the full html, there are some unused items currently, but I do plan on adding more of them soon.
My next plan is to incorporate images into the objects, so a picture loads for each selection option. How would I manage that?
[ ] is used for arrays, which are indexed with numbers. If you want named properties, you should use an object, which uses { } for its literals:
var favWebComics = {
Goblins: "www.goblinscomic.org",
GirlGenious: "www.girlgeniousonline.com",
GrrlPower: "www.grrlpowercomic.com"
};
= is for assigning to variables, not specifying property names in an object.
Then you need to understand the difference between . and [] notation for accessing objects. .x means to look for a property literally named x, [x] means to use the value of x as the property name. See Dynamically access object property using variable.
So it should be:
document.getElementById("web").innerHTML = favWebComics[x];
your array is not structured correctly and an object would be better suited:
var favWebComics = {
Goblins : "www.goblinscomic.org",
GirlGenious : "www.girlgeniousonline.com",
GrrlPower : "www.grrlpowercomic.com"
};
then you should be able to access the properties as you intend
favWebComics.Goblins
favWebComics.GirlGenious
favWebComics.GrrlPower
Technically you were treating the array like a dictionary. if you're going to do that but still wanna add more information later you'll need to use brackets {} on the code.
var favWebComics = {
Goblins: ["www.goblinscomic.org"],
GirlGenious: ["www.girlgeniousonline.com"],
GrrlPower: ["www.grrlpowercomic.com"]
};
Also for javascript, as long as your searching key value stores, use braces [] for the call. Here's the working code below.
document.getElementById("web").innerHTML = favWebComics[x];
I have your solution, that displays:
the selected choice
the url
the images
Please check the fiddle.
http://jsfiddle.net/nw8Ln6ha/13/
Your object would be:
var favWebComics = {
Goblins : {url:"www.goblinscomic.org", img:"img1"},
GirlGenious : {url:"www.girlgeniousonline.com", img:"img2"},
GrrlPower : {url:"www.grrlpowercomic.com", img:"img3"}
};
Your display code:
document.getElementById("demo").innerHTML = "You selected: "+x+" "+ eval("favWebComics[\""+x+"\"].url")+" "+ eval("favWebComics[\""+x+"\"].img");

Need to get an array of the names of all applicationScope variables

In an application I am working on I need to get a list of the names of all applicationScope variable then I need to cycle through them and filter out the ones starting with a know string say $xyx. I thought that the applicationScope.keySet().
I'm using this code for starter:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
if (itr.hasNext()){
var str:String = itr.next();
dBar.info(str,"Value = ");
}
if I put the variable col in a viewScope it shows a list of all the keys. but when I run the script the values displayed in the dBar info are not the keys but some other information that I'm not sure where it comes from.
I should just be able to iterat through the list of keys, am I missing something?
This code is in the before page loads event
After some poking around and experimenting I got this to work:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
while (itr.hasNext()){
var str:Map.Entry = itr.next();
if (str.substring(0,9) == "$wfsLock_"){
//do stuff
}
}
so I'm now a happy camper.
Although your code works in SSJS, it is not correct (and that's why I don't like SSJS...).
The applicationScope is an implementation of the java.util.Map interface and the keySet() method returns a Set containing the keys in that Map. Every entry is (probably) a String (other data types like integers are actually also valid). The line
var str:Map.Entry = itr.next();
doesn't cast it to a Map.Entry: it doesn't really do anything: str remains a string.
The Map interface also has an entrySet() method that returns the entries (Map.Entry). You can use that to retrieve the key as well as the value:
var it = applicationScope.entrySet().iterator();
while (it.hasNext()) {
var entry = it.next();
print( entry.getKey() + " = " + entry.getValue() );
}
(in this code the print() line will use the toString() method of the key as well as the value to send information to the console)
I see from your code that you've installed my XPages Debug Toolbar. You can also use that to quickly check what's in the scopes and what the actual datatype is.

Set nested model attribute with a variable as a key

I am using DeepModel to access nested attributes in a Backbone.js model. So this works fine:
this.model.set({'chart_configs.mentions_bar_graph.date': "cats"});
However, I'd like to use a variable as part of my key so like:
this.model.set({'chart_configs.'+ this.chartName + '.date': "cats"});
Is this some how possible? I know that I can do it by
this.model.attributes.chart_configs["mentions_bar_graph"].date = "cats";
But that, obviously, does not trigger a "change" event else where in my code.
thanks!
Model#set can be called in two ways:
m.set('key', 'value');
m.set(an_object_of_keys_and_values);
So you should be able to get past the "you can't define an object literal like that" problem by using the first form of Model#set:
this.model.set('chart_configs.' + this.chartName + '.date', 'cats');
If DeepModel doesn't like that then you could do it the long way:
var values = { };
values['chart_configs.' + this.chartName + '.date'] = 'cats';
this.model.set(values);
An object is an object whether it has a name or not and set only cares about the keys and values.

Javascript Computed Values With Arrays

Jquery Each Json Values Issue
This question is similar to above, but not the same before it gets marked duplicated.
After realasing how to use computed values i came across another issue.
In my javascript i have the following code:
var incidentWizard = ['page1.html','page2.html','page3.html'];
var magicWizard = ['page1.html','page2.html','page3.html'];
var loadedURL = 'page1.html';
The input to this function would be (true,'incident')
function(next,wizardname)
{
var WizSize = incidentWizard.length;
wizardName = [wizardName] + 'Wizard';
var wizardPOS = jQuery.inArray(loadedURL,incidentWizard);
And now i want to use the wizardname parameter to decide what array i am going to use...
Loader(incidentWizard[wizardPOS],true);
Ive also tried
Loader([incidentWizard][wizardPOS],true);
and
Loader([incidentWizard][wizardPOS],true);
Also the loader function just required the string value in the array at wizardPOS sorry for confusion
But when trying this i always end up with the outcome...
/incidentWizard
I know this is something to do with using computed values but i've tried reading about them and cant seem to solve this issue.
Basicly i want to use the computed value of wizardName to access an an array of that name.
Please help supports, looking forward to seeing many ways to do this!
On this line:
wizardName = [wizardName] + 'Wizard';
You are attempting to concatenate the string 'Wizard' to an Array with one string element "incident". I'm assuming you just want regular string concatenation:
wizardName = wizardName + 'Wizard';
However, now you only have a string, not an array instance. To fix that, change the way you define your *Wizard arrays to something like:
var wizardyThings = {
incidentWizard : ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then your function (which is missing a name as it stands), becomes:
function someMethod(next, wizardname) {
wizardName = wizardName + 'Wizard';
var wizSize = wizardyThings[wizardName].length;
var wizardPOS = jQuery.inArray(loadedURL, wizardyThings[wizardName]);
...
}
You can only access properties of objects that way. For global values, window[ name ] will work. For simple local variables it's just not possible at all. That is, if inside a function you've got
var something;
then there's no way to get at that variable if all you have is the string "something".
I would just put each array as a prop on an object:
var obj {
incidentWizard: ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then you can just do obj['incidentWizard'] or obj.incidentWizard this will return:
['page1.html','page2.html','page3.html']

dump jquery object in an alert box

I am not quite adept in maneuvering jQuery, and it came to a point that I need to debug a program that was passed down from me without a documentation.
I have this var a, an object, that I really want to know the content of its collection. In my mind I need a function like foreach() in PHP to iterate over this object variable. Upon researching I end up in using jQuery.each(). Now I can clearly iterate and see what was inside var a.
However, it was kind of annoying to alert once every value on the var a. What I wanna know if it's possible to display all the contents in just one pop of alert box?
Here is my code:
$.each(a, function(index, value) {
alert(index + ': ' + value);
});
The var a contains infos such as:
creationdate: date_here
id: SWFUpload
modificationdate: date_here
type: .jpg
index: 0
name: uploaded_filename.jpg
size: size_in_bytes
BTW: The var a is called via file upload script.
Why don't you just accumulate the values in an array, then display the whole array (for instance, using JSON)? Example:
var acc = []
$.each(a, function(index, value) {
acc.push(index + ': ' + value);
});
alert(JSON.stringify(acc));
In any case, I'd suggest using a debug tool like Firebug. So you could just use console.log(a) and be able to navigate freely through the objects's fields.
In firefox you could try:
alert(yourObject.toSource());
OR you could use some plugin:
See: jQuery Dump Plugin

Categories

Resources