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;
Related
I would like to add new medication that contains "medc name, medc dose, medc dur"
I used update but the problem is the first argument. Im giving it a non-existing name so it adds it to the existing medications
the right syntax is "medication.avamys : medArr 'that contains the dose and dur'"
but this part "medication.avamys" is varying
so what can I do?
You will want to use the JavaScript syntax to use an expression as the property of an object.
...update({
["medication."+medcName]: medArr
})
Note the expression is in square brackets, and becomes the name of the field written to the document.
Note also that you are not required to build the object within the call to update(). You can build the object in a different statement, and pass it to update(). This is effectively the same thing, and probably more readable if you have lots of properties to assign:
const data = {}
data["medication."+medcName] = medArr
...update(data)
I am trying to return the value under the key 'str' in an Object but I am having trouble accessing the value.
This is what is returned in the console:
Currently I am using a map function to go over the array and just return the _str value like so:
let idx = currentArray.map(function(x) {
return x._id._str;
});
However it is still returning the value as an object. How can I get just the value of the _str key?
Here is the full array without specifying the id field. This is what is returned if you jsut return 'x' in the map function.
You've clarified that the screenshot is of x._id. So to access _str, you'd use x._id[0]._str: The _str property is in the object referenced by the 0 property (the first entry in the array x._id refers to).
Note that in general, _-prefixed properties are meant not to be accessed by code outside the code responsible for the objects in question. You don't seem to be responsible for them, so accessing those properties is likely to make your code rely on undocumented properties that may change in the next "dot" release of whatever lib you're using. It's just convention, but it's a very common convention.
If you right click on the property, most browser consoles offer the ability to copy property path.
Based on this SO post and the docs, it appears that you can probably use x._id.str.
If I understand correctly, you are receiving the str value but it is an object instead of the string literal. In other words, you are getting _str: "598..." instead of "598....". A possible solution would be to use the mongo javascript function to convert the str value to a string.
In your case, I think something like return x._id.str; may work as _id is a MongoID.ObjectID.
I've also linked the documentation below for reference.
https://docs.mongodb.com/manual/reference/method/ObjectId/
Here's a relevant SO answer as well: Convert ObjectID (Mongodb) to String in JavaScript
I think you should write x[_id]._str because _id is one of the array objects.
I"m trying to teach my self coding for some mapping work, and I cannot seem to wrap my head around this.
I have a JavaScript function that is called from a button:
This code connects my button using DOJO:
on(dom.byId("metro"), "change", updateLayerVisibility);
The following code correctly turns my layer off (metro is defined elsewhere)
function updateLayerVisibility(){
metro.setVisibility(false);
}
However if i try to use a variable I get an error that "test.setvisiblity is not a function"
function updateLayerVisibility(){
var test = "metro";
test.setVisibility(false);
}
So my question is what is the difference between these two? why isn't "metro" substituted for "test"? If its because the variable is a string, what should it be converted to.
Thanks (and sorry for the strange question)
In your above example, test is just a string and strings don't have a method named setVisibility. However a metro object (apparently) does.
The methods available to strings can be seen here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Methods
metro is an identifier. In that context it is a variable. It will have a value, in this case, that value is an object with a property setVisibility that has (in turn) a value that is a function.
test is also an identifier and a variable. It has a value, which is the string "metro". The string has no connection to the variable metro and it doesn't have a setVisibility property.
The key part of your question is where you say "metro is defined elsewhere". As already suggested by others, your metro object is not just a string with a value (as your test object is) but a reference to a particular type of object which has particular functions such as setVisibility.
I think I see what you want to do: programmatically turn individual layers on and off. If you know the layer ID then you can get a reference to a layer using:
var layer = map.getLayer(id);
(where map is your reference to the ArcGIS map object and id is the string name of the layer to return. So if you had a layer with the id "metro" you would get it with:
var layer = map.getLayer("metro");
Here you can substitute the string passed in to the getLayer method for any other string value that represents the id of a layer you want.
Once you've got your layer object you can then set it's visibility in the same way as you were with the metro layer reference:
layer.setVisibility(false);
Hope this helps!
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]()
I'd really like to track variables without switching between Firebug console windows or clicking around so much, so I want to draw a runtime viewer of variable names and their corresponding values that will display on the page of the app I am building.
I'd like to two functions, show(variableName) and freeze(variableName). They will output both the variable's value and the name of the variable or object as a literal string which will serve as the text label in the viewer. freeze(variableName) is the same as show(variableName) except with a setTimeOut timer for tracking loops.
I'm sure I'm missing something basic, but I haven't found out a way to get the string that comprises the name of a value programmatically so I can use it as a label. I guess I could create the table with hardcoded labels prior to runtime and just populate it with values at runtime, but I really want to generate the table dynamically so it only has those variables I specifically want to show or freeze. Simple functions:
foo1 = "Rock";
show(foo1);
foo2 = "Paper";
show(foo2);
foo3 = "Scissors";
show(foo3);
should output this via getElementById('viewer-table'):
<table>\<tr><td>foo1</td><td>Rock</td></tr><tr><td>foo2</td><td>Paper</td></tr><tr><td>foo3</td><td>Scissors</td></tr></table>
I've tried this solution:
How to convert variable name to string in JavaScript?
and eval() but it's not working for me...I dunno, shouldn't this be easy? Getting frustrated...
Thanks,
motorhobo
I am not sure you can actually get the "name" of the variable that is being passed into a function for two reasons:
1) The variable is just an identifier. In fact, you could have multiple identifiers reference the exact same object. You are (generally) passing that reference, not any actual object.
2) The show/freeze function is going to stomp on the identifier name, either through named arguments in the function declaration or by referencing them through the arguments array.
I was trying to think if there was some clever way to use the arguments.callee or the stack property on an exception in Firefox... but I can't see anything that would expose the arguments as you desire.
What I would recommend is to simply add the name of the variable and its value to a simple object, and call one of the various jsDump methods (I prefer the one in QUnit):
function show(o) {
document.getElementById("viewer-table").innerHTML = QUnit.jsDump(o);
}
// actually use the method
show({"foo1":foo1});
There's no easy way to solve this as the called function simply doesn't know the original name of the variable. You couldn't solve this with reflection even (esp. in javascript) so you'll have to pass the name of the variable to the function too. To follow the link you posted:
function show(varObject)
{
for(name in varObject)
{
alert(name + ": " + varObject[name]);
// save both name and reference to the variable to a local "to observe array"
}
}
And call it with
var test = "xxx";
show({'test' : test});
Within the for loop you could add easy variable to a monitor array and update your gui in fixed time intervalls (you can't be notifed when a signle variable changes it's value. You need some kind of global monitor/observer which exactly you're trying to create).