Using a variable to name another variable javascript - javascript

In the process of making a discord bot using node.js and discord.js, I've come to a point where I want to create a new variable, in this case an object with one property (the string "server" and some string for a value.) To name said new variable, I want to use the server ID of the server I'm referring to here, which is stored in another variable. What is a way I can do this?
So far I've tried
eval("var " + serverID + " = {'server': 'test'}"), which gave me a syntax error: invalid/unexpected token on the second plus sign (replacing the object with a string still gave me the same error). Everywhere I've looked hasn't been helpful in explaining what is wrong with the eval function, and I'm confused as to how I would do this another way.
In case the first thing that came to your mind was restructuring how I'm working with variables and the types I'm using, whatever this outputs must let me add more information to this variable, which at least in my mind restricts me to using Objects and adding properties. I also store this variable to a JSON file later in the code which also restricts me to using either Arrays or Objects.

I'm going to guess that the eval fails because your serverID is a number (or a string that represents a number), so the statement would look like var 123 = {'server': 'test'}, which would give a syntax error.
In any case, a simple alternative would be to create a property on an object instead of a variable. Something like:
var myVariables = {};
//...
myVariables[serverID] = {'server': 'test'};
You could even add it to the global object, if it makes sense for your situation and you really need a global variable.

There is no good reason to to store a variable as the name of another variable. The simplest way to accomplish what you want, as you mentioned, is storing the serverID in the object.

Your syntax is correct, although you may want to ensure that your server ID is a legal JavaScript identifier.
var serverID = "asddkjkisdf";
eval("var " + serverID + " = {'server': 'test'}")
console.log(asddkjkisdf);
I would however recommend creating a data structure like an array of objects to store this information. In that case you wouldn't have to worry about the value of your server ID. E.g.
[{id: 'asdfasdf', server: 'test'}, ... ]

Related

How can I get the key as well as the value when using db.js to query IndexedDB?

I have an IndexedDB of changes. I add an item like this, and then log the result to check the key has been created successfully:
_this._idb.add('steps', step).done(function (items) {
var item = items[0];
_logger.log("ADDED STEP", { id: item.__id__, step: item }, "CT");
});
The output from this is as expected:
...as you can see, the id has been added to the object when it is stored.
However, when I query the db to getback a list of objects, using this code:
this._idb.steps.query('timestamp').bound(start, end).execute().done(function (results) {
_logger.log("Results", results, "CT");
}
I don't get the id as part of the object that is returned:
... and the lack of id makes updating and deleting impossible.
How can I get the id of the item when I query indexed db using db.js - or am I approaching this in the wrong way, and is there something else I should be doing?
(Note: I'm using TypeScript to compile the JS, but I don't think that's especially relevant to this question)
This is expected behaviour, you're only going to get the __id__ property if you don't define a keyPath in your db schema.
Because there's no keyPath defined the value is not associated with it in indexeddb, it's only added to the resulting object after it has been added, because at that point in time we know the auto-incremented value that IndexedDB has assigned to it.
Since the value isn't really part of the object I don't have any way to assign it to the object when it comes out during a query, maybe I could use the position in the array but that's more likely to be wrong than right.
If you want the ID to be persisted against the object then you need to define a keyPath as part of the object store schema and the property will be added to the resulting object and available and it will be on the object returned from a query.
Disclaimer - I wrote db.js
Looking at the source, __id__ is only defined when your keyPath is null in the add() method. From what I'm seeing, you'll never see this in a query() response.
In IDB null keyPaths are allowed only when using auto-incrementing ("out-of-line") keys. So if you're getting the object back, it should have an auto-incrementing key on it or some other keyPath.
The __ prefix in JavaScript usually means the developer intended it to be a "private" property. I'm guessing this is for internal use and you shouldn't be counting on this in your application code.
Consider using explicit, so-called "in-line" keys on your object store.
The goal of db.js is easy and simple to use. Your is advanced use case.

Safely using eval to use variable as an object name

As shown in this example
javascript-use-variable-as-object-name
I am using eval to use a DOM attribute to select an element from an array. Though there is no direct way for the user to change the input, I want to be as secure as possible and make sure that the variable is indeed an integer before I evaluated it.
Which of the following would be the best, most secure, way?
$(".listitem").click(function(){
var id = $(this).attr("record-id");
if(!isNaN(new Number(id))){
Storage.search.nearby.currec = rowsHolder[eval(id)];
}else{
// send email to admin, shut down
}
});
or
$(".listitem").click(function(){
var id = $(this).attr("record-id");
if(parseInt(id)){
Storage.search.nearby.currec = rowsHolder[eval(id)];
}else{
// send email to admin, shut down
}
});
More, but not required info:
Basically I am pulling down a large JSON string from online, containing an array of records. Upon building a table from the info using a for statement ( for(i in array) ), I push each row into an array called rowsHolder and give the tr an attribute of record-id="i". Then when the user clicks the row, I call the method you see above. I am using PhoneGap with JQuery Mobile.
As always, thanks for the input
-D
There is absolutely no reason to use eval here.
If your id is kind of a number, use parseFloat(id) to get it. Unnecessary as it would be converted back to a string when used as a property name, though.
If your id is an integer, use parseInt(id, 10) to get it. Unnecessary as it would be converted back to a string when used as a property name, though.
If your id is a string, just let it be a string. The property name you use it for would be one anyway.

javascript variable variable names and global scope (pinesnotify)

I'm using pines notify (somewhat irrelevant to my issue, I imagine) to create notifications on the change event of a drop down list. On the server side, the change is saved to a database, then when the save is complete - I wish to remove the notification (or do something else depending on the result).
The problem is in creating the notification object in a way that I can later reference it (to remove it).
My intended solution would obtain the id of the dropdownlist, prepend 'pn' to it and use that as the variable name, much like
var pnid = 'pn' + $('#mydropdown').attr('id');
notifications[pnid] = createNotification();
In the codebehind I can create javascript code knowing what the notification object will be called. However I'm struggling with my 'notifications' object.. I've tried this[notifications], window[notifications] etc. to no avail (ie I cannot later reference this object to interact with it) . I'm creating that object outside of any functions like so
var notifications = {};
Am I going about this the completely wrong way?
You can use this line before reaching notifications object.
window.notifications = window.notifications || {};
This will help you create the object if it is undefined and it will also prevent you from overriding it if it already exists.
Note : I assume you have to use this object as a global variable.

How to dynamically create / destroy JS variables and append / remove their values in a string

I want to create javascript variables on the fly and append their values into a string. I actually am unable to find a method which dynamically declares variables in javascript. Once that is done I would want to do the reverse of this. So my question has two parts : one is related to creating and deleting variables on the fly as per requirement and the other is related to appending or deleting those variables value into a string at a specific point in the string.
There is the eval function.
But! you should ask yourself twice why do you need to "create variables on the fly"
eval on MDN
If I understand what you're after correctly, you should use an object for this:
var o = {};
o.name = "value"; // Creating a property
delete o.name; // Deleting a property
It sounds like you have a specific problem, could you perhaps share a bit more information about your problem?

passing a variable into a json collection

I'm trying to call the following js method. I wish to pass in the variable siteid. I can alert this value. But it doesn't seem to work in the following context. ie if just add the id 1234 it works.
alert(siteid);
embedSWF ('flashcontent', '{"siteID":siteid,"siteType":"portal","mainSWF":"http:\/\/tv.xxx.net\/flash\/xxx1.swf","movieWidth":"426","movieHeight":"276","expressInstall":"http:\/\/tv.xxx.net\/expressInstall.swf"}');
You need to concatenate the value of siteid into your string: '...' + siteid + '...'
Depending on what you're building, you may want the string to have quotes around the value.
The most robust way to do this is to first make the object as a normal object and then serialize it:
var parms = {siteID: siteid, siteType: "portal", ...};
embedSWF('flashcontent', JSON.stringify(parms));
If you need to support outdated browsers that don't have the built-in JSON object, there are several implementations available online.
embedSWF ('flashcontent', '{"siteID":'+siteid+',"siteType":"portal","mainSWF":"http:\/\/tv.xxx.net\/flash\/xxx1.swf","movieWidth":"426","movieHeight":"276","expressInstall":"http:\/\/tv.xxx.net\/expressInstall.swf"}');
You're passing a string:
'{"siteID":siteid,"siteType":"portal","mainSWF":"http:\/\/tv.xxx.net\/flash\/xxx1.swf","movieWidth":"426","movieHeight":"276","expressInstall":"http:\/\/tv.xxx.net\/expressInstall.swf"}'
You probably mean to pass:
'{"siteID":' + siteid + ',"siteType":"portal","mainSWF":"http:\/\/tv.xxx.net\/flash\/xxx1.swf","movieWidth":"426","movieHeight":"276","expressInstall":"http:\/\/tv.xxx.net\/expressInstall.swf"}');
It seems a little weird to pass a JSON string, rather than the associative array itself. Either way, that's your problem, above.

Categories

Resources