Is there a way to print dynamic variables? - javascript

I am coding in node.js atm. I need to create a dynamic variable and invoke it.
e.g.:
username = 'im_a_user';
global['ws[' + username + ']'] = ws; //(yes, i want to store the connection with ws module)
but
ws[im_a_user].send('blabla');
doesn't work and node shuts down. So I want to know how global['ws[' + username + ']'] looks like for debbuging.
Do you know how I can print it - or even better, why im_a_user in ws[im_a_user].send('blabla'); isn't defined?
Thanks for your time!

Accessing object property is possible with brackets, but you have to give it a valid expression: a string literal or a variable. Looks like you are referencing a variable that is not defined. That's where Node chokes.
So try either with a variable that is defined
var key = 'im_a_user'
ws[key].send('blabla');
or a string literal
ws['im_a_user'].send('blabla');

Related

How do I create a custom javascript variable that selects part of an already existing javascript variable?

I am trying to create a custom javascript variable in GTM that returns part of a javascript variable that already exists.
Variable that already exists: window.ShopifyAnalytics.meta.product.variants.0.name
returns this: "Bamboo Basic String - Schwarz - S"
However I want to code a custom javascript variable to just return the Schwarz part, is this possible? If so what is the code that I would need?
Please can someone let me know what code to put into GTM to create this variable?
TIA
If all names are pretty much the same you could use split to get that part of string and then remove whitespaces. It would look like this:
window.ShopifyAnalytics.meta.product.variants.0.name.split('-')[1].replace(/
/g,'');
If the already existing variable is always structured the same way you could do something like this:
let variable = window.ShopifyAnalytics.meta.product.variants.0.name.split('-')
Then by calling varaible[1] you get the 'Schwartz' part of the variable.
If you want a return value you can use a function like the following and call it wherever you want.
Simply make sure to pass the correct argument content
// Declaring a function getColor that returns the second element in the list,
// trimmed (without spaces before and after)
const getColor = (content) => {
return content.split('-')[1].trim();
}
const test = "Bamboo Basic String - Schwarz - S";
console.log(getColor(test));
//console.log(getColor(window.ShopifyAnalytics.meta.product.variants.0.name));
You could split the string on the hypens (-) like this:
const productName = window.ShopifyAnalytics.meta.product.variants.0.name;
const part = productName.split(' - ')[1];
Assuming you have a consistent format, and you always want the second part after that hyphen.
split will separate parts of a string into an array where it finds a match for the argument. The first index [0] will be the product name, the second [1] will be the part you're looking for.
This could cause issues if you have a product name with a - in it too though so use with care!
If it needs to be an anonymous function for GTM, you could try the following (though I'm not a GTM expert):
function () {
const productName = window.ShopifyAnalytics.meta.product.variants.0.name;
return productName.split(' - ')[1] || 'Unknown';
}

Unable to get value of JavaScript Object [duplicate]

I'm looking for an easy way to assign to a variable depending on the value of another variable.
device.slot2_clipList[clipNumber] = singleClipDetails;
what I'm trying to do is: replace the "2" with another variable, so that i can run the same operation while just changing the
var slotNumber, and write to the corresponding variable.
i tried
device.slot + device.slotNumber + _clipList[clipNumber]
but (obviously?), this doesn't work.
How can this be done? (Maybe I named the Question incorrectly, but that was the closest I could think of.)
Thanks
This is what bracket notation is for
var i = 2;
device['slot' + i + '_clipList'][clipNumber] = singleClipDetails;
device['slotNumber' + _clipList[clipNumber] ]
Explanation:
foo.bar in javascript is identical (even in performance) to foo['bar']. So any object property name can be built up from strings.

How to call a function defined as a string?

I want to define functions and scripts in a database record then using Javascript convert the database field from a string to code.
I was thinking I could use 'eval', but this doesn't seem to work.
As an example:
var strTest = "function(strParams) { alert('hello: ' + strParams); };"
,fn = eval(strTest);
fn("World");
This doesn't work, eval returns undefined, hopefully this gives the idea of what I am trying to achieve.
The problem is that eval parses your function as a function declaration. But function declarations require a name.
Instead, you should make it a function expression, which doesn't require one.
var strTest = "(function(strParams) { alert('hello: ' + strParams); })";
eval(strTest)("World");
Only do this if you trust the string.
Alternatively, you may be interested in the Function constructor:
var f = Function("strParams", "alert('hello: ' + strParams)");
f("World");
You could try something like this:
<script src="http://my-server/js-func/foobar.js"></script>
and have the server serve up the JS retrieved from the DB at that endpoint.

ExecuteScript doesn't work for localStorage when using variable

I am trying to pass in a variable to use for executeScript as shown below:
var groupScript = '\'' + 'localStorage.setItem("groups", "[' + groupNames + ']"); + '\'''
which when printed to the console gives me:
'localStorage.setItem("groups", "[\\"lunch\\"]");'
If I try to run:
browser.executeScript( groupScript );
It doesn't create the localStorage variable. However, if I run the following (which just has the value of the variable), it does work:
browser.executeScript( 'localStorage.setItem("groups", "[\\"lunch\\"]");');
Can someone let me know what I need to do in order to get it to work with passing in the variable? Trying to create localStorage variable for my protractor test. Thanks!
There is a special arguments array containing the list of arguments passed into a script:
browser.executeScript('localStorage.setItem("groups", arguments[0]);', groupNames);

Changing Attributes of json object in Android application (Titanium)

Hi I am developing Android application using Titanium.I want to change value of particular attributes of json object.I tried following code :
var row_jsonfeed = this.responseText;
var jsonfeed = eval('('+row_jsonfeed+')');
my jsonfeed object look like this :
{"feeds":
[
{"username":"abc","user":"abc","feed":{"description":"dss","id":660,"user_id":1}},
{"username":"bcd","user":"bcd","feed":{"description":"dddd","id":659,"user_id":1}}
]
}
I want to change username value so I tried like this:
jsonfeed.feeds[0].username = "xyz";
alert(jsonfeed.feeds[0].username);
But it's not working.It not giving me changed value of username.Any other alternative way to do this. Instead of eval I also tried JSON.parse but that also not working.So i need proper way to do this.Thank you in advance.
I think the problem is with your call to eval. You forgot to concatenate your parens:
eval('(' + row_jsonfeed + ')');

Categories

Resources