How do I show an entire javascript object as a string? - javascript

As a feature in a sort of game created in HTML5/CSS in combination with javascript, I would like to show some randomly looking code which scrolls in a div.
An easy way to accomplish this would be to actually print the code used to create the game, but I cannot seem to manage to do so.
I have tried to call .toString() on an object I have defined, but it only prints [Object Object], which obviously isn't preferably. The desired effect is basically the same as calling .toString() on a single function, however I would like to do so on the entire code/all objects that I use.
How could I accomplish this?
Edit:
Some clarification, I have an object
var Foo = {
stuff: [],
function1: function() { /* code */ }
}
And I would like to be able to use it as follows:
var string = Foo.toString();
$("#myDiv").html(string);
Which will result in myDiv containing the source code of the object called Foo.

This is the answer you are looking for:
How to inspect Javascript Objects
You have to navigate the object, there is no function as PHP's var_dump.

here is something you could use :
var a = {'some':'strange','object':''};
console.log( JSON.stringify(a) );
// outputs : {"some":"strange","object":""}
If your game is targeting IE > 9, then you could further randomize the string with something like (base64 encode/decode):
var a = {'some':'strange','object':''};
console.log( btoa(JSON.stringify(a)) );
// outputs : eyJzb21lIjoic3RyYW5nZSIsIm9iamVjdCI6IiJ9

Related

Jint (.NET javascript parser) always returns ExpandoObject

I try to write a mod for a game. This is totally new territory for me, so I might be on the wrong track here.
The game is written in Unity and you are able to add a .script file to your mod. The .script file can contain javascript that is parsed by Jint.
I tried to output a simple string from one of the game DLLs:
var UnityEngine = importNamespace("UnityEngine");
var IceEngine = importNamespace("IceEngine");
var GameMain = importNamespace("GameMain");
var output = GameMain.Game.ModPath;
UnityEngine.Debug.Log("----- Testmod Output Start-----");
UnityEngine.Debug.Log(output);
UnityEngine.Debug.Log("----- Testmod Output End-----");
In the GameMain.dll it says:
public class Game : MonoBehaviour, IUserManagerListener, IAccountMsg, IMsg, IRenderListener
{
private static string modPath = Game.userPath + "/Mods";
// lots of other code...
public static string ModPath
{
get
{
return Game.modPath;
}
}
My understanding is that GameMain.Game.ModPath should give me a string. But instead the output in the log file is this:
----- Testmod Output Start-----
System.Dynamic.ExpandoObject
----- Testmod Output End-----
No matter wehat I try to output, I get a System.Dynamic.ExpandoObject and don't know what to do with it.
Maybe someone can give me tips/resources to help. :)
The ExpandoObject is the nearest equivalent that .Net has for a JavaScript Object - that is an object to which members can be added or removed on-the-fly.
This suggests to me that the underlying JavaScript method is actually returning an object rather than a string.
You can use Newtonsoft.Json to serialize the object:
var json = (string)JsonConvert.SerializeObject(GameMain.Game.ModPath);
Which will allow you to see if there's a property you should be using. So let's say this gives you {"modPath":"..."}, you should access that property directly like this:
var modPath = (string)GameMain.Game.ModPath.modPath;

JavaScript - Unable to get property from an Array of Object over function(parameters)

I have an Array of Objects:
var keywordset = [
{word:["PO","Pending Order"],message:["Do you need to post registry?"]},
{word:["delete"],message:["Do you want to delete in system?"]},
{word:["contact"],message:["Inter-related feature: Contact Management"]}
]
Also, I created a function to convert the strings in an array of objects to UpperCase:
function ObjectArrayUpperCase(arrayname,array1){
console.log(arrayname[0])
console.log(array1)
for(b=0;b<arrayname.length;b++){
for(c=0;c<arrayname[b].array1.length;c++){
arrayname[b].array1[c] = arrayname[b].array1[c].toUpperCase()
}
}
}
Then, i run the ObjectArrayUpperCase() function by passing parameter into it
ObjectArrayUpperCase(keywordset,'word')
Unfortunately, the ObjectArrayUpperCase() function unable to process "array1" part, seems like unable to recognize it. But the "arrayname" working as expected, because if i replace "array1" to "word", the function work.
I tried to change the parameter but still no luck:
ObjectArrayUpperCase(keywordset,'word')
ObjectArrayUpperCase(keywordset,word)
ObjectArrayUpperCase(keywordset,keywordset.word)
etc...
Please advise how to pass the correct parameter to the function
You need square brackets to evaluate an expression like array1 to be used as the property name.
for(var b=0;b<arrayname.length;b++) {
// -----------------------v------v--- and likewise below
for(var c=0;c<arrayname[b][array1].length;c++){
arrayname[b][array1][c] = arrayname[b][array1][c].toUpperCase()
}
}
}
Otherwise, how could it know if you meant to use the variable or an actual property with that name?
Also, be sure to declare your variables explicitly. I used var above.
Lastly, the loops can be written a little more cleanly using modern syntax and methods like this:
arrayname.forEach(obj => obj[array1] = obj[array1].map(s => s.toUpperCase()))

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.

how to pass a function name via JSON and call it in javascript/jQuery?

I have a JSON string which includes a function I need to call.
My JSON looks like this:
{
"type":"listview",
// the function I would like to call
"content":"dynoData.getRetailers()",
"custom_classes":["","nMT pickList","",""],
"lib":"static_listview.html",
"tmp":"tmp_listview_inset",
"lang":"locale_search",
...
I'm using this to assemble a jQuery Mobile listview on the client. To get the dynamic data, I need to call dynoData.getRetailers().
However I'm struggling to make the call :-)
This is what I'm trying:
var dyn = $.parseJSON( passed_JSON_string ),
content = dyn.content;
I had hoped calling it would trigger the function but it just returns the function name as a string.
Question:
How can trigger the actual function?
Thanks!
EDIT:
I'm putting the JSON string on the HTML element on the actual page, which I will replace with the element I'm building. Here is the HTML:
<ul data-template="true" data-config='{
"type":"listview",
"content":"dynoData.getRetailers()",
"custom_classes":["","nMT pickList","",""],
"lib":"static_listview.html",
"tmp":"tmp_listview_inset",
"lang":"locale_search",
"theme":"c",
"filter":"true"
}'></ul>
I could put all of these into data- attributes, but that would be messy...
Solution:
This worked:
1) change JSON to:
..."method":"getRetailers", ...
2) call from Javascript:
content = dynoData[ dyn.method ]();
Thanks everyone!
Assuming the function is always part of the dyn object you can use notation like following to call a function:
dyn['dynoData']['getRetailers']();
So if you are able to adjust json you could send back something like:
"content":{ "mainObject": "dynoData" , "method" :"getRetailers"}
And translate it to your dynamic function using variables:
dyn[content.mainObject][content.method]();
As an example using jQuery try using the following :
$('div')['hide']();
Which is the same as :
$('div').hide()
As charlietfl pointed out you can use object notation to call functions. For your case you have to get rid off () and split it, then call it like this;
jQuery(function($) {
var temp = $('ul').data('config').content.replace(/\(\)/g, '').split('.');
window[temp[0]][temp[1]]();
});
However this could solve your problem, if you think about future, you have to extend it a little bit. This way even you don't know the depth, you can call it anyway;
jQuery(function($) {
var temp = $('ul').data('config').content.replace(/\(\)/g, '').split('.'), func, i, il = temp.length;
for(i = 0; i < il; i++) {
if(func == null) {
func = window[temp[i]];
continue;
}
func = func[temp[i]];
}
func();
});
Try ConversationJS. It makes dynamic calls pretty easy and its a great way to decouple your codebase: https://github.com/rhyneandrew/Conversation.JS
JSON is purely data notation to be passed around so it is easily read and parsed, therefore it has no concept of functions. However, there are other ways of dealing with this and if you are starting to think that that is the only way to deal with your dilemma, then take a step back and examine your design. Instead of using this:
eval(yourCode);
Try this
var tempFun = new Function(yourCode);
tempFun();

Categories

Resources