JSON Weirdness Needs More Elegant Approach - javascript

Basically, I'm working on a page that includes four different JSON "thingies" (objetcs,arrays). Forgive my lack of proper terminology.
When I get the JSON, it comes in as an object with a bunch of sub-objects, and each "sub-object" looks like this:
"token":"government",
"title":"Government",
"isSelected":false,
"type":"CATEGORY",
"subtype":"INDUSTRY",
"count":12
So the first task is to loop through each JSON and populate a box full of checkboxes, using the title as the label and the isSelected to indicate the checked status. So far, so good.
BTW, somewhere aslong the way, I picked up a JS script that checks whether an object is JSON or an array, and according to that "quick & dirty" test, my object is an array. Or an array object (you know, the one is created with [ ] and the other with { })?
Anyway, when the end user checks and un-checks checkboxes, I need to keep track of it all and immediately send back changes to the server (when the user clicks a DONE button). The crazy thing is that by looping through the objects, I was able to change the isSelected value to true . . . just not back to false.
for(var i = 0; i < $array.length; i++){
$array[z].isSelected = true;
}
Perhaps I was up too late when I worked on all of this, but using the same approach, I could not change $array[z].isSelected to false when the checkbox got de-selected.
In the end, I converted the JSON "thingy" to a string, search and replaced the corresponding values, and then converted the string back into an object. This is all working now, but I feel as though I've just used up a roll of duct tape on something that could have been put together by snapping the pieces together nicely.
Question: Did I miss the boat totally and is there a simple way to change values of JSON objects?
If so, could you point me in the right direction?

That JSON thingy is just a string representation of a javascript object.
One way of creating an object is
var myObject = {
"myName": "AName",
"myType": "AType"
};
This object can be referenced as myObject, with the properties myObject.myName and myObject.myType containing values AName and AType.
You should be able to just reference the object by name as objName.token objName.title etc.
If you have trouble try parsing the json with javascript then reference the result as above. This should make it easier for you to access, manipulate or delete data in the objects properties as well.
The nesting of these as below can be referenced as myObject.moreProperties.prop1 etc
var myObject = {
"myName": "AName",
"myType": "AType",
"moreProperties": {
"prop1": "vaue1",
"prop2": "vaue2",
}
};

Related

Why I don't see all the keys and values of an object when its keys are long strings?

I have an object that I populate with with very long keys (strings that are around 400 chars long).
When I try to print the object
console.log(Object.keys(myCoolObject))
or
console.log(myCoolObject)
I can only see TWO of the keys (when in fact I should see around 20 of them). The keys are there though, because I when I try to access the data in the object with any of the keys, it does work.
console.log(myCoolObject['aVeryVeryLongKeyHere'])
Does anyone know what is going on?
Why are you using long keys? The longer the keys the longer the lookup will take when the object grows and grows.
But that's besides the point. If you want to print very long keys I suggest you modify your approach.
The "native" logging doesn't show all the data you need/want because it truncates the keys as they go "off screen". So you need to iterate manually through the object with the long keys, then print out the key, then print out the value.
Luckily you can work with comma's in console.log, so you can chain multiple debugging things in one go. If you look at the example below, you see I first print the key name as string, then I print the value with the native console.log printing, not losing the possibility to drill down into the value.
Press look at the display in the browsers console(press f12).
var key, CoolObject = {
'BysodelightofshowingneitherbelievehepresentDealsighupinshewawaywhenPursuitexpressnoorpreparerepliedWhollyformedoldlatterfuturebutwaysheDayherlikewisesmallestexpensesjudgmentbuildingmancarriagegayConsideredintroducedthemselvesmrtodiscretionatMeansamongsawhopesforDeathmirthinohlearnheequalonBysodelightofshowingneitherbelievehepresentDealsighupinshewawaywhenPursuitexpressnoorpreparerepliedWhollyformedoldlatterfuturebutwaysheDayherlikewisesmallestexpensesjudgmentbuildingmancarriagegayConsideredintroducedthemselvesmrtodiscretionatMeansamongsawhopesforDeathmirthinohlearnheequalonBysodelightofshowingneitherbelievehepresentDealsighupinshewawaywhenPursuitexpressnoorpreparerepliedWhollyformedoldlatterfuturebutwaysheDayherlikewisesmallestexpensesjudgmentbuildingmancarriagegayConsideredintroducedthemselvesmrtodiscretionatMeansamongsawhopesforDeathmirthinohlearnheequalon' : { 'hello' : 'hi'},
'AffrontingimprudencedoheheeverythingSexlasteddinnerwantedindeedwishedoutlawFaradvancedsettlingsayfinishedrailleryOfferedchieflyfartherofmynocolonelshynessSuchonhelpyesomedoorifinLaughterproposallaughinganysonlawconsiderNeededexceptuppiquedanAffrontingimprudencedoheheeverythingSexlasteddinnerwantedindeedwishedoutlawFaradvancedsettlingsayfinishedrailleryOfferedchieflyfartherofmynocolonelshynessSuchonhelpyesomedoorifinLaughterproposallaughinganysonlawconsiderNeededexceptuppiquedanAffrontingimprudencedoheheeverythingSexlasteddinnerwantedindeedwishedoutlawFaradvancedsettlingsayfinishedrailleryOfferedchieflyfartherofmynocolonelshynessSuchonhelpyesomedoorifinLaughterproposallaughinganysonlawconsiderNeededexceptuppiquedanAffrontingimprudencedoheheeverythingSexlasteddinnerwantedindeedwishedoutlawFaradvancedsettlingsayfinishedrailleryOfferedchieflyfartherofmynocolonelshynessSuchonhelpyesomedoorifinLaughterproposallaughinganysonlawconsiderNeededexceptuppiquedan' : {'world':'planet'},
'HeshareoffirsttoworseWeddingsandanyopinionssuitablesmallestnayMyhehousesormonthssettleremoveladiesappearEngrossedsufferingsupposingherecommenddoeagernessCommandednoofdependingextremityrecommendattentiontolerablyBringinghimsmallestmetfewnowreturnedsurpriselearningjenningsObjectiondeliveredeagernessheexquisiteatdoinWarmlyuphenearermrmerelymeHeshareoffirsttoworseWeddingsandanyopinionssuitablesmallestnayMyhehousesormonthssettleremoveladiesappearEngrossedsufferingsupposingherecommenddoeagernessCommandednoofdependingextremityrecommendattentiontolerablyBringinghimsmallestmetfewnowreturnedsurpriselearningjenningsObjectiondeliveredeagernessheexquisiteatdoinWarmlyuphenearermrmerelymeHeshareoffirsttoworseWeddingsandanyopinionssuitablesmallestnayMyhehousesormonthssettleremoveladiesappearEngrossedsufferingsupposingherecommenddoeagernessCommandednoofdependingextremityrecommendattentiontolerablyBringinghimsmallestmetfewnowreturnedsurpriselearningjenningsObjectiondeliveredeagernessheexquisiteatdoinWarmlyuphenearermrmerelymeHeshareoffirsttoworseWeddingsandanyopinionssuitablesmallestnayMyhehousesormonthssettleremoveladiesappearEngrossedsufferingsupposingherecommenddoeagernessCommandednoofdependingextremityrecommendattentiontolerablyBringinghimsmallestmetfewnowreturnedsurpriselearningjenningsObjectiondeliveredeagernessheexquisiteatdoinWarmlyuphenearermrmerelyme': {'and':'or'},
'SighviewamhighneathalftowhatSentlateheldthansetwhywifeourIfanblessingbuildingsteepestAgreementdistrustsmrssixaffectionsatisfied.DayblushesvisitorendcompanyoldpreventchapterConsiderdeclaredoutexpensesherconcernsNoatindulgenceconvictionparticularunsatiableboisterousdiscretionDirectenoughoffotherssayeldestmayexetershePossibleallignorantsuppliedgetsettlingmarriagerecurredSighviewamhighneathalftowhatSentlateheldthansetwhywifeourIfanblessingbuildingsteepestAgreementdistrustsmrssixaffectionsatisfied.DayblushesvisitorendcompanyoldpreventchapterConsiderdeclaredoutexpensesherconcernsNoatindulgenceconvictionparticularunsatiableboisterousdiscretionDirectenoughoffotherssayeldestmayexetershePossibleallignorantsuppliedgetsettlingmarriagerecurredSighviewamhighneathalftowhatSentlateheldthansetwhywifeourIfanblessingbuildingsteepestAgreementdistrustsmrssixaffectionsatisfied.DayblushesvisitorendcompanyoldpreventchapterConsiderdeclaredoutexpensesherconcernsNoatindulgenceconvictionparticularunsatiableboisterousdiscretionDirectenoughoffotherssayeldestmayexetershePossibleallignorantsuppliedgetsettlingmarriagerecurredSighviewamhighneathalftowhatSentlateheldthansetwhywifeourIfanblessingbuildingsteepestAgreementdistrustsmrssixaffectionsatisfied.DayblushesvisitorendcompanyoldpreventchapterConsiderdeclaredoutexpensesherconcernsNoatindulgenceconvictionparticularunsatiableboisterousdiscretionDirectenoughoffotherssayeldestmayexetershePossibleallignorantsuppliedgetsettlingmarriagerecurred' :{'universe':'galaxies'}
}
console.log('truncated keys because they are too long for display');
console.log(CoolObject);
console.log('truncated keys because they are too long for display');
console.table(CoolObject);
console.log('Showing by iterating the keys');
for(key in CoolObject) {
if(CoolObject.hasOwnProperty(key)) {
console.log(key,':', CoolObject[key]);
}
}
Ok so the problem didn't have anything with long keys, but as #Weedoze guessed (Thanks!) I was filling the object inside an async function, and since I wrote my console.log inside this function, I was seeing the object before it received all the data.

Return Array of Data using Google Assistant from Firebase

The structure I have for my firebase database is like this:
fruits:
apple,5
banana,6
I want to put apple and banana in an array so that when i give a command to Google Assistant, it would give me apple, 5 and banana, 6. The code I have is like the one below:
function handleCommand(agent) {
return admin.database().ref('Fruits').child().once("value").then((snapshot) =>{
var i;
var fruitlist=[];
//puts each snapshot child of 'Fruit' in an array
snapshot.forEach(function(item) {
var itemVal = item.val();
fruitlist.push(itemVal);
});
//outputs command in google assistant
for (i=0; i < fruitlist.length; i++) {
agent.add(fruitlist[i]);
}
})
The default response is "not available".
I get the following in the execution logs:
Firebase.child failed. Was called 0 aruguments. expects at least 1.
I do not know which argument to put inside the Firebase.child. if i want all fruits to be "spoken" by Google Assistant. Below is a picture of my firebase structure.
The error looks like the one below:
What I am currently doing now to just output the fruits are manually entering each child in the code like this and removed the ".child" in the return statement:
Which gives me the output below which is also what I want to see but using arrays as the solution I am using now is very much hardcoded:
As the error message suggests, and as you surmise, the child() call expects a parameter - in particular, the name of the child node you want to get information from. However, since you want all the children of the "Fruits" node - you don't need to specify it at all. The child() call just navigates down through the hierarchy, but you don't need to navigate at all if you don't want to.
The snapshot you get back will have a value of the entire object. In some cases, this can be pretty large, so it isn't a good idea to get it all at once. In your case, it is fairly small, so not as big a deal.
On the JavaScript side, you can now handle that value as an object with attributes and values. Your original code didn't quite do what you said you want it to, however - you're getting the value, but ignoring the name (which is the attribute name or key). You can iterate over the attributes of an object in a number of ways, but I like getting the keys of the object, looping over this, getting the value associated with the key, and then "doing something" with it.
While I haven't tested the code, it might look something like this:
function handleCommand(agent) {
return admin.database().ref('Fruits').once("value").then((snapshot) =>{
// Get an object with all the fruits and values
var fruits = snapshot.val();
// Get the keys for the attributes of this object as an array
var keys = Object.keys( fruits );
// Iterate over the keys, get the associated value, and do something with it
for( var i=0; i<keys.length; i++ ){
var key = keys[i];
var val = fruits[key];
agent.add( `The number of ${key} you have are: ${val}` );
}
})
While this is (or should be) working Firebase and JavaScript, there are a couple of problems with this on the Actions on Google side.
First, the message returned might have some grammar problems, so using your example, you may see a message such as "The number of Apple you have are: 1". There are ways to resolve this, but keep in mind my sample code is just a starter sample.
More significantly, however, the call to agent.add() with a string creates a "SimpleResponse". You're only allowed two simple responses per reply in an Action. So while this will work for your example, it will have problems if you have more fruit. You can solve this by concatenating the strings together so you're only calling agent.add() once.
Finally, you may wish to actually look at some of the other response options for different surfaces. So while you might read out this list on a speaker, you may read a shorter list on a device with a screen and show a table with the information. Details about these might be better addressed as a new StackOverflow question, however.

format json data in javascript like a pivot table

I have the the following data being returned by my api.
[{"category":"Amazon","month":"Feb","total":9.75},
{"category":"Amazon","month":"Mar","total":169.44},
{"category":"Amazon","month":"Apr","total":10.69},
{"category":"Amazon","month":"May","total":867.0600000000001},
{"category":"Amazon","month":"Jun","total":394.43999999999994},
{"category":"Amazon","month":"Jul","total":787.2400000000001},
{"category":"Amazon","month":"Aug","total":1112.4400000000003},
{"category":"Amazon","month":"Sep","total":232.86999999999998},
{"category":"Amazon","month":"Oct","total":222.26999999999998},
{"category":"Amazon","month":"Nov","total":306.09999999999997},
{"category":"Amazon","month":"Dec","total":1096.2599999999998}]
I want to format it so that the months are all grouped under each category like this:
[{"category":"Amazon","month":{"Jan":9.75,"Feb":9.75,"Mar":9.75,"Apr":9.75,etc...}]
How can I do this with javascript?
What I'm ultimately trying to do is to display some pivoted data in a table. I'm not sure what the best design is to accomplish this.
Right now, I'm just setting up a table dynamically and adding in the data corresponding to each row. Are there better design patterns for doing this?
You can reduce the array of objects to an object using the categories as keys, and adding the months, and then map it back to an array again
var arr = [{"category":"Amazon","month":"Feb","total":9.75},
{"category":"Amazon","month":"Mar","total":169.44},
{"category":"Amazon","month":"Apr","total":10.69},
{"category":"Amazon","month":"May","total":867.0600000000001},
{"category":"Amazon","month":"Jun","total":394.43999999999994},
{"category":"Amazon","month":"Jul","total":787.2400000000001},
{"category":"Amazon","month":"Aug","total":1112.4400000000003},
{"category":"Amazon","month":"Sep","total":232.86999999999998},
{"category":"Amazon","month":"Oct","total":222.26999999999998},
{"category":"Amazon","month":"Nov","total":306.09999999999997},
{"category":"Amazon","month":"Dec","total":1096.2599999999998}];
var o = arr.reduce( (a,b) => {
a[b.category] = a[b.category] || [];
a[b.category].push({[b.month]:b.total});
return a;
}, {});
var a = Object.keys(o).map(function(k) {
return {category : k, month : Object.assign.apply({},o[k])};
});
console.log(a);
I would take the following approach:
Write down on a piece of paper how to solve the problem (the "algorithm").
Flesh out this algorithm with more details. Sometimes this is called "pseudo-code".
Convert the pseudo-code into JavaScript.
For instance, your algorithm might look like this:
Create a new thing to hold the results.
Loop through the elements in the input.
For each element in the input, update the results thing.
Return the result.
Sometimes it helps to read out the algorithm aloud to yourself. Or animate the algorithm on a blackboard. Or talk through the algorithm with someone nearby.
The pseudo-code might be:
Create a new array containing a new object to hold the results, with a category property set to "Amazon", and a months property set to an empty object.
Loop through the elements in the input array.
For each element, add a new property to the months property of the results object, whose key is the value of the month property from the element, and whose value is the value of the total property from the element.
Return the result.
If you have specific questions about any of those steps, you can research it further, or ask, such as:
How do I create a new array, with an object inside?
How do I loop through the elements of an array?
How do I retrieve a property from an object?
How do I add a new key/value pair to an object?
How do I return the result?
If you are unfamiliar with any of the terms used above--such as array, object, property, key, value, or element--research them and make sure you know what they mean. Knowing and using correct terminology is the first step to successful programming!
When converting your algorithm into JS, write it step by step, and test it at each phase. For instance, start with a version which doesn't loop over the input at all, and make sure it produces a correct output of [{category: "Amazon", month: {}}]. Walk though your code in the debugger at this and each following step--if you don't know how to use the debugger, learning that should be your first priority! If you want to check a little bit of syntax, to make sure it does what you think, just try it out by typing it into the console. If you don't know what the console is, learning that should be another top priority.
All the above assumes that you've got a single Amazon category. If you are going to have multiple categories, and want multiple objects (one for each) in your output array, then start over from the top and write the algorithm and pseudo-code which can handle that.

First javascript project with Durandal. Trying to get data from 3rd party API

So i'm working on a project where players of a game will be able to compare their performance with those of their peers at the same skill level. I can get a prototype of the code to work outside of a durandal structure, but when I try to follow along with other examples while supplying my own sources for the data, I just can't get it all together.
Here is my code:
define(function (require) {
var http = require('plugins/http'),
ko = require('knockout');
var url = 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/',
key = '?api_key=#################################';
return {
name: ko.observable,
getSummoner: function() {
var that = this;
if (this.name.length > 0) {
return;
}
return http.jsonp(url + name + key, 'jsoncallback').then(function(response){
that.name(response.items);
});
}
};
});
Replace the #'s with my personal API key that the host recommends I don't share. I'll supply one if necessary and just change it later.
I have 2 specific questions here:
I got the function structure from a tutorial. I don't know why I need to check for length with the IF statement. What is that returning exactly?
This api call returns a JSON object with a nested object inside. What I want, is to display the keys and values from the nested object as li's on the view. Right now I can't even get it to tell me if its actually grabbing the object in the first place.
Here is my HTML:
<section>
<h2>Hello! What user would you like to investigate?</h2>
<form class="form-inline">
<fieldset>
<label>Name</label>
<input type="text" data-bind="value: name, valueUpdate: 'afterkeydown'"/> <!--Text input box-->
<button type="submit" class="btn" data-bind="click: getSummoner, enable: name">Click Me</button><!--This button has both a class and an ID,
Css is linked from index.html-->
<ul data-bind="foreach: name">
<li data-bind="text:$data"></li>
</ul>
</fieldset>
</form>
</section>
What I expect to see is just 1 bullet item that either says object or whatever name is fed into the input box. What I get is nothing.
The returned object (with my username attached) looks like this:
{"ryebrush":{"id":25500750,"name":"RyeBrush","profileIconId":551,"summonerLevel":30,"revisionDate":1426533699000}}
I want to be able to access the ryebrush.id, ryebrush.profileIconId, and so on and so forth. Help?
EDIT: Also, this comes pre-loaded in the input box:
function (b){function c(){if(0<arguments.length)return c.Ka(d,arguments[0])&&(c.P(),d=arguments[0],c.O()),this;a.k.zb(c);return d}var d=b;a.N.call(c);a.a.sa(c,a.m.fn);c.o=function(){return d};c.O=function(){c.notifySubscribers(d)};c.P=function(){c.notifySubscribers(d,"beforeChange")};a.s(c,"peek",c.o);a.s(c,"valueHasMutated",c.O);a.s(c,"valueWillMutate",c.P);return c}
Uhhhhhh.....what?
You sort of asked two questions, so I'm sort of going to give you two and a half answers.
Before we address your first question, you are using the knockout observable function incorrectly, and that is going to cause you lots of headaches. Let's fix that. The following two lines of code will both work similarly. When you call the observable function, you create a new instance of an observable. If you call it with no arguments, the value of the observable is undefined. Since we know you want a string here, it may be preferable to initialize it to the empty string, as in the second example.
name: ko.observable(),
or
name: ko.observable(''),
Then, we can set or retrieve the value of the observable by calling it as a function:
that.name('value');
and
that.name() == 'value';
I got the function structure from a tutorial. I don't know why I need
to check for length with the IF statement. What is that returning
exactly?
After the if statement, you have the following line of code:
http.jsonp(url + name + key, 'jsoncallback')
If name is undefined or empty, you will attempt to make this call to one of two urls respectively:
https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/undefined/?api_key=#
or
https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name//?api_key=#
We know that both should return an error (probably a 400), so there's no point in making those calls. The if statement, when applied to a string, is true when the string is initialized and empty. Note, this will throw an error if the string is undefined, and that's no good.
However, the syntax is also wrong. Technically, the value of that.name is a function and, when treated as a string, will evaluate as
function (b){function c(){if(0<arguments.length)return c.Ka(d,arguments[0])&&(c.P(),d=arguments[0],c.O()),this;a.k.zb(c);return d}var d=b;a.N.call(c);a.a.sa(c,a.m.fn);c.o=function(){return d};c.O=function(){c.notifySubscribers(d)};c.P=function(){c.notifySubscribers(d,"beforeChange")};a.s(c,"peek",c.o);a.s(c,"valueHasMutated",c.O);a.s(c,"valueWillMutate",c.P);return c}
Recall from above, a much better thing to write in the if statement is
if (!that.name())
We call the function to get the value. Both '' and undefined are falsey in javascript, and so the if statement will catch both cases and exit, which is what we want. Note it will also exit if the value of name is 0, or any other falsey javascript value.
This api call returns a JSON object with a nested object inside. What
I want, is to display the keys and values from the nested object as
li's on the view. Right now I can't even get it to tell me if its
actually grabbing the object in the first place.
There are a number of things wrong with your view.
<ul data-bind="foreach: name">
This will iterate through the value of that.name. If that.name is 'ryebrush', this will (I believe), iterate through each letter. That's no good. If your goal is to have a list of summoners in that.name, you will want to swap ko.observable with ko.observableArray. You may also want to change the name that.name to that.names to avoid confusion.
<li data-bind="text:$data"></li>
This is right if your array is filled with strings. foreach will iterate through each item in the array, and $data is each item. However, if the item is in fact an object, you can reference properties on the item. For example, if each item in your array is
{"id":25500750,"name":"RyeBrush","profileIconId":551,"summonerLevel":30,"revisionDate":1426533699000}
then, since name is a property on the object, you can reference name in your view
<li data-bind="text:name"></li>
Finally, you're not actually getting the data in the right place after your http call. If the response to your http call is
{"ryebrush":{"id":25500750,"name":"RyeBrush","profileIconId":551,"summonerLevel":30,"revisionDate":1426533699000}}
Then you would want to write
return http.jsonp(url + name + key, 'jsoncallback')
.then(function(response){
that.name(response["ryebrush"]);
});
If the response is instead an array of items
[{"ryebrush":{"id":25500750,"name":"RyeBrush","profileIconId":551,"summonerLevel":30,"revisionDate":1426533699000}}]
Then you would want to write
return http.jsonp(url + name + key, 'jsoncallback')
.then(function(response){
that.name(response[0]["ryebrush"]);
});
Conclusion
Unfortunately, this isn't a great question. I can't tell exactly what's going on with the API you're using, so I can't tell you exactly what you should write. To accomplish what you're trying to do, you'll need to spend a little bit of time reading up on javascript, knockout, and durandal. Here are some good resources for each:
javascript
knockout
durandal
However, I see you're a new user. I want to encourage you not to get discouraged. It'll take a bit of time to to learn the ropes, but it's worth it. Don't give up. I hope this helps!

Convert string to name of object (casting)

I want to cast a string to an existing object.
Background: I am using only JS, no libraries and no server side code. I have existing objects with elements I wish to display. I pass the name of the object using a query string so it arrives as a string. Example ?Room=Cube and what I wind up with is
nextRoom = getQueryString(); // which returns a string
and I want to display the Cube object. However nextRoom contains "Cube" and JS is not helpful, if I call a display function:
display(nextRoom)
Javascript treats it as a string and fails. Currently I fake it out with the object:
castToObj{"Cube":Cube, "Other":Other, "Etc":Etc, ........}
.....
room = castToObj[nextRoom]; // accessing the object returns the room Object
then I can display the room by calling:
display(room); // now JS treats the parameter as an object
But this requires me to rewrite code to modify the castToObj{} contents every time I add a room. I would like a way to turn "Cube" into Cube, in other words turn a string into an object. I have tried many variations but have been unsuccessful. I could list ways I have tried but that seems senseless because they were all failures.
HELP! PLEASE!
P.S I retired about twenty years ago before learning C++, OOP, etcetera so my javascript skills are just my "C" programming experience expanded.
First create an empty container object:
myElements = {};
Then change your code wherever you define an element, from
Cube = ... whatever ...
to
myElements.Cube = ... whatever ....
for all of your elements (Other, Etc ...).
After this, you simply use
nextRoom = getQueryString();
display(myElements[nextRoom]);
You can use java script eval function but depending on the situation it might open your program to XSS attack. You should use it carefully.

Categories