Using a dynamically created variable to access named object in an object - javascript

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]()

Related

How do I access the 'str' value in my object?

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.

Javascript objects with JSON

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;

variable in javascript statement

How does one add a variable string in this javascript statement?
where name may correspond to any valid string , say WebkitTransform or Moztransform,etc
document.getElementById('test').style.VARIABLE_NAME = 'rotate(15deg)';
My code doesn't seem to work when i set the VARIABLE_NAME to WebkitTransform, but it works fine if I use WebkitTransform directly, as in without naming it via a variable.
Thanks in advance :)
There are two ways to access members of a Javascript object.
Dot notation, which uses an identifier to access the member:
obj.member;
Bracket notation, which uses a string to access the member:
obj['member']
The latter uses a string to locate the member and you can just as easily use any expression. The value of the expression will be converted to a string so these are equivalent:
obj[{}]
obj['[object Object]']
If your expression is already a string it will be used as is, and in your case your variable holds a string so you can just do:
document.getElementById('test').style[VARIABLE_NAME] = 'rotate(15deg)';
There are 2 ways of accessing values in javascript objects. The first one is by using the dot operator(e.g. object.memberName). The second one is by using the square bracket notation(e.g. object['memberName']).

JavaScript colon operator

I am trying to learn JavaScript. After reading this page: What does ':' (colon) do in JavaScript?
I tried to replace
var store = new dojo.data.ItemFileReadStore({
url: "countries.json"
});
with
var store = new dojo.data.ItemFileReadStore();
store.url = "countries.json";
It does not work. Can any one please point out the mistake, or explain the correct use of the Colon operator?.
Thanks.
That's not a fair comparison, although you're almost there.
var store = new dojo.data.ItemFileReadStore({
url: "countries.json"
});
//Creates a new store object, passing an anonymous object in with URL
// property set to "countries.json"
The alternative without the colon operator is:
var props={};
props.url="countries.json"
var store = new dojo.data.ItemFileReadStore(props);
//Does same as above but doesn't use :
Not this isn't the only use of : in JavaScript though, it can also be used in the ternary operator (alert(b==c?'equal':'not equal');) and in labels (for example in case statements)
The first passes url parameter to the so-called constructor or the object, which may do something under the hood with it - for example assign it to other variable or property, for example "url2".
The second assigns url property of that object and you don't know if it will be used.
In first code you are creating a new object and passing it to the function as an argument.
While in second part you are running the function and then, you are setting property of store object.
They are totally different thing, as you are not calling function with argument, so it might not run properly. and you are setting return of function to object. not setting property.
In this case, the object literal in your first example is being used to pass in a set of options to the constructor. Constructing the ItemFileReadStore and then trying to set those options may not be equivalent since it may need them in order to build the object to begin with.
You'd need to do something like this to replace : with =:
var options = {};
options.url = 'countries.json';
var store = new dojo.data.ItemFileReadStore(options);
If the second way isn't working, you're probably not returning an Object with new dojo.data.ItemFileReadStore(); which prevents you from extending it with dot syntax. If you have an Object, adding to it like that will work fine.
Edit: Misread, in one you're passing an argument, in the other you're assigning to the return value, so two different things, I'll leave the above as an FYI.
The dojo.data.ItemFileReadStore object probably requires that the url property be present while the object is being created. If that's not the case, then the object doesn't allow you to set that property manually after you have already initialized the object.
The colon is used in JSON to designate the different between a key and a value, when you pass an object structure ({}).

Javascript Object Access

I am using a Comet Push Engine called APE (Ajax Push Engine) and whenever I receive a realtime event I receive it in an javascript object called 'raw'.
So if for example if the raw object contains a 'location' value, I can print 'raw.location' and it will give me the value,
alert(raw.location);
So I have another object called currentSensor, which contains a value like this (in my example it would contain the string 'location'):
currentSensor.value
How do I programmatically use the currentSensor.value variable to access the 'raw' object? I have tried this:
var subsensor = currentSensor.sensorKey;
and then
alert(raw.subsensor);
But I keep getting undefined because the raw object doesn't contain a key called "subsensor" its actually "location". I hope this makes sense!
Thanks!
When using dot-notation, you use a literal property name. If you want to use a string, use square bracket notation.
foo.bar === foo['bar'];
Strings can be variables.
baz = 'bar';
foo.bar === foo[baz];
like this:
console.log(raw[currentSensor.value]);
Here you go:
alert(raw[subsensor]);
The dot syntax cannot help you when you need to access variable indexes. You need to use the array access method.
Note: The dot access method is just syntactic sugar and is not really needed in any place, but it is useful for code readability.
For your entertainment:
"1,2,3"["split"](",")["join"]("|")

Categories