I'm trying to replicate a "feature" of PHP (And in most languages) in Javascript.
Here it is in PHP:
$objectName = 'ObjectA';
$someObject->$objectName->someMethod();
Basically using a string variable to reference an object variable.
So in Javascript, I was hoping to do something like:
var objectName = "ObjectA";
someObject.[objectName].someMethod();
Anyone know how to do this? Or if its even possible?
You almost have it, just remove the first ., like this:
var objectName = "ObjectA";
someObject[objectName].someMethod();
If you want to search for more info around this, it's called bracket notation.
Related
I have a bunch of CSS properties stored in a MySQL database accessed via PHP. I need to make these properties available to JavaScript after the page has finished loading.
So what I did is foreach row, put the values in a Javascript object like so:
foreach ($cellcontent as $cellproperty) {
echo 'var '.$cellproperty->cell_id.' = {cellwidth:"'.$cellproperty->cell_width.'"};';
}
(For simplicity's sake I've only included one object property here but in reality there are many more.)
My problem is that at runtime, via JavaScript I get the cell_id reference which is somewhere in the html page like so:
var dacell = $(this).closest("div");
var cellid = dacell.attr("id");
So at this point, cellid is equal to the name of my var from the php output.
But when I try to get the property of my object (cellwidth) via JavaScript it doesn't work. Says its undefined when I try to see the value in an alert:
alert(cellid.cellwidth);
I think I'm just not referencing the actual object at this point and just trying to get a property of what has now become a string.
Is there a way to get back the reference to the object itself?
var cellid = dacell.attr("id");
The variable cellid is a string. Your hopes would be that the variable your are looking is in the global namespace which you can access via the following:
window[cellid].cellwidth
It's an awfull practice to pollute the global namespace with so much stuff.
Fetch all the values you need to inject into the JS, create an associative Array and inject it as a single JSON into the Page.
Nevermind everyone. The eval() javascript function fixed it all.
Instead of doing:
alert(cellid.cellwidth);
I did:
alert(eval(cellid).cellwidth);
and everything worked.
Thanks for all your time.
Cheers,
Erick P.
finalVariables() returns an object that contains data accessible by .dataName notation i.e. finalVariables().mainViewWindow0 returns the string stored for mainViewWindow0. I'm trying to access mainViewWindow0 using a dynamically created variable, but for obvious reasons this doesn't work so well with dot notation, but I don't know how to work around it. Help to be had for me?
Please ignore the poor coding practice of having a hard-coded number in there; I promise to get rid of it later
activePane = dot.id.substring(6); //gets dot # and sets it as active pane
var tempForPaneNumber = "mainViewWindow" + activePane + "";
document.getElementById("mainViewWindowContent").innerHTML = finalVariables().###this is where I want to use
the string from "tempForPaneNumber" to access ###
finalVariables[tempForPainNumber]()
Should do the trick if I understand correctly.
In Javascript you can access properties of an object either through the dot notation or through the use of brackets to specify the identifier for the property so myVar.foo is equivalent to myVar['foo']. Therefore, if I understand what you are asking correctly you want to use finalVariables()[tempForPaneNumber]()
If I have a string like
var s = someString;
But I do NOT know the value of that string, since the program obtains it from external file, and I wanted to use that string to access an objects property, like:
alert(obj.s)
//or
alert(obj[s]);
How would I do that? The code I wrote doesn't work, the alerts are just empty (and I'm positive that s is NOT empty AND that there is a property with the same value as s). But when I try to access an object normally it works fine (using a property name I already know):
alert(obj.name);
//or
alert(obj["name"]);
So...any ideas? Thanks
Im sure this must have been asked before but I can't find an example on SO.
I have a JSON string that starts out life as something like this:
{"model":"14","imgsize":"890","selection":{"SC":"BC","PC":"AC"},"changed":{"PC":"AC"}}
The string needs to be changed on user input such that "selection" records all the input the user has click on and "changed" is the last thing the user clicks on.
So I have a function that reads the JSON string from a textarea, modifies it dependant on what the user has selected (node and value) and then writes it back to the text area for debugging.
function changeJSON(node, value) {
json = JSON.parse($('#json').val());
json.selection[node] = value;
delete json.changed;
json.changed = {node:value};
$('#json').val(JSON.stringify(json));
}
"selection" works nicely but "changed" updates to the literal variable name I pass it (in this case node) I.e. if I called the function with changeJSON("BC","HC") the JSON string becomes:
{"model":"14","imgsize":"890","selection":{"SC":"BC","PC":"AC","BC":"HC"},"changed":{"node":"HC"}}
I understand what javascript is trying to do but I want the changed element to be what my variable contains i.e.
,"changed":{"BC","HC"}
and not
,"changed":{"node","HC"}
I'd love someone to tell me what I am doing wrong!?
EDIT
Solved - see below for Quentin explanation as to why and my answer for the code changes necessary - hope it helps others.
I don't think this is the same question, mine is why the literal variable name is used rather than the contents of the variable
The question referenced explains how to resolve the issue, but since you are asking for an explanation.
A variable name is a JavaScript identifier.
A property name in object literal syntax is also a JavaScript identifier (although you can use a string literal instead).
Since an identifier cannot be both a variable and a property name at the same time, you cannot use variables for property names in object literal syntax.
You have to, as described in the referenced question, create the object and then use the variable in square bracket notation.
The solution, as Quentin suggested is to create th object first i.e.
delete json.changed;
json.changed = {};
json.changed[node] = value;
By JSON text, I mean the return value of JSON.stringify. I know how to do this with JSON object, but I couldn't figure out how to do this with JSON text (add new attribute/element, say "sn":"1" to JSON text, but its structure is kept and I don't need to stringify it again), can anyone help me?
Thanks!
I don't know why you'd want to do this - why not just add the property before you stringify it?
But if you must, given a string that contains JSON:
var myJSON = '{"prop1":"val1","prop2":"val2"}';
You can easily add a property to the beginning by doing this:
myJSON = '{' + '"sn":"1",' + myJSON.substr(1);
Or add it to the end:
myJSON = myJSON.replace(/}$/, ',"sn":"1"' + '}');
Or use whatever other combination of String manipulation functions takes your fancy...
If you want to add the new property in a specific place within the string, say inside a nested object or array or something, well, again some kind of regex or combination of .indexOf() and .substr() or something could do it, but really I think it's nuts to approach it this way.
Obviously the above code can be wrapped up in a function, and '"sn":"1"' can be replaced with a parameter or variable name or whatever - but why?
Note also that I've assumed above that there will be at least one existing property and inserted a comma accordingly- up to you to make that smarter if you want to allow for empty objects.
P.S. There aren't "JSON strings" and "JSON objects": all JSON is a string. In JavaScript one way of creating objects is with the object literal syntax that inspired JSON, but there's no such thing as a JSON object.
It makes no sense to do it the way you're suggesting... just turn it back into an Object, add your field and stringify it again! Or am I missing something?
You're going to have to parse it somehow. The most straightforward way is probably un-stringifying it to object/array/literal data. But if you don't want to do that, you could either use regular expressions, or methods of the String object like substr to manipulate the string directly.