First question, might be dumb, be easy on me.
So I have an object creator followed by a set of variables, a-z, which create 26 objects with names a-z. I have a piece of code which generates a random letter from a-z and i would like to display a property of the randomly picked object, but the letter is generated as a string, and "a".type comes out as undefined (understandably). so i need to take that string, and remove the quotes from it basically so i can use it. i found somewhere on here someone said ("a").charAt(0) would work but it doesn't in my case. heres a very simplified version of the code
function Object(type) {
this.type = type;
};
var a = new Object("annoying");
var random = "a";
console.log((random).type);
I just want it to log "annoying" but i believe that chance.character is making it log "a".type instead of a.type. So i need a way to turn the string ito a usable piece of code so i can refer to the variable.
Unless I'm misunderstanding the question, you should be able to store your objects by their corresponding letter (as a key) in a containing object like so:
var letterObjects = {};
function letterObject(type) {
this.type = type;
};
letterObjects["a"] = new letterObject("annoying");
var random = (chance.character);
console.log(letterObjects[random].type); //annoying
Related
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';
}
I have looked at many of the posts involving this kind of question but I have not been able to find anything that works in this situation.
I have a variable x, it is an integer given the following value.
let x = Math.ceil(Math.sqrt(characterNumber));
My goal is to segment a string into array elements of the desired length. Using integers I can do so like the following.
let secondMessage = newMessage.match(/.{1,3}/g);
My ideal solution would be for the following to work, however whatever I am trying returns as null. In my code editor, when I pass anything that is not an integer (x in this case) the colour of the inside {} changes.
let secondMessage = newMessage.match(/.{1,x}/g);
I have tried creating a RegExp, however that also returns null.
Thank you for any answers and sorry for the long (possibly repeated) question.
Variables aren't expanded inside regular expressions. You need to construct the regular expression dynamically by creating a string and then calling new RegExp().
let x = 3;
let rx = new RegExp(`.{1,${x}}`, 'g');
let newMessage = 'abcdefghij';
let secondMessage = newMessage.match(rx);
console.log(secondMessage);
I have a JavaScript object that looks like this:
var map = {
Monday: [
'something',
'something else',
],
};
When trying to access it, I noticed something strange I don't understand:
Doing console.log(map.Monday); returns undefined. To get the array back, I need to do console.log(map["Monday"]);.
Why is this? I already tinkered with quotes and uppercase/lowercase identifiers. The only time I encountered this so far was when there were numbers involved in the identifier (but of course it was still a string).
Edit
According to the comments it's working – indeed that is correct. Then the reason is probably related to the fact that the array identifier comes from an HTML select element:
$('.select').on('change', function(event) {
var selectedDay = $(event.currentTarget).val();
if (map.hasOwnProperty(selectedDay)) {
console.log(map[selectedDay]);
}
});
Then the reason is probably related to the fact that the array identifier comes from an HTML select element.
Yes… the syntax someObj.property is equivalent to someObj['property'], i.e. the property name is passed as a string in square brackets there.
Now if you want to dynamically access some property, and only have the property name as a string, then you need to use the square bracket syntax. For example:
var day = 'Monday';
console.log(map[day]);
The map[day] is equivalent to map['Monday'] which is equivalent to map.Monday. But if you were to call map.day, you would try to access map['day'], i.e. a property day in your object which obviously doesn’t exist.
What do we learn from this question? It’s a good idea to simplify the code in order to focus on the problem instead of including lots of irrelevant things. But when you do, you should make sure that the problem actually exists in the simpler code example. Because in this case, you eliminated the problem because you thought it doesn’t matter that you are trying to access the property dynamically.
In javascript both objects and arrays can be accessed as arrays and also as objects:
var a = []; //array
a["x"] = 100; //works
a.y = 50; //works
a.z = a.x + a["y"]; //works
var b = {}; //object
b.x = 10; //works
b["y"] = 20; //works
b["z"] = b["x"] + b.y; //works
If you still have a problem it's not related to the code you posted.
In an application I am working on I need to get a list of the names of all applicationScope variable then I need to cycle through them and filter out the ones starting with a know string say $xyx. I thought that the applicationScope.keySet().
I'm using this code for starter:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
if (itr.hasNext()){
var str:String = itr.next();
dBar.info(str,"Value = ");
}
if I put the variable col in a viewScope it shows a list of all the keys. but when I run the script the values displayed in the dBar info are not the keys but some other information that I'm not sure where it comes from.
I should just be able to iterat through the list of keys, am I missing something?
This code is in the before page loads event
After some poking around and experimenting I got this to work:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
while (itr.hasNext()){
var str:Map.Entry = itr.next();
if (str.substring(0,9) == "$wfsLock_"){
//do stuff
}
}
so I'm now a happy camper.
Although your code works in SSJS, it is not correct (and that's why I don't like SSJS...).
The applicationScope is an implementation of the java.util.Map interface and the keySet() method returns a Set containing the keys in that Map. Every entry is (probably) a String (other data types like integers are actually also valid). The line
var str:Map.Entry = itr.next();
doesn't cast it to a Map.Entry: it doesn't really do anything: str remains a string.
The Map interface also has an entrySet() method that returns the entries (Map.Entry). You can use that to retrieve the key as well as the value:
var it = applicationScope.entrySet().iterator();
while (it.hasNext()) {
var entry = it.next();
print( entry.getKey() + " = " + entry.getValue() );
}
(in this code the print() line will use the toString() method of the key as well as the value to send information to the console)
I see from your code that you've installed my XPages Debug Toolbar. You can also use that to quickly check what's in the scopes and what the actual datatype is.
Jquery Each Json Values Issue
This question is similar to above, but not the same before it gets marked duplicated.
After realasing how to use computed values i came across another issue.
In my javascript i have the following code:
var incidentWizard = ['page1.html','page2.html','page3.html'];
var magicWizard = ['page1.html','page2.html','page3.html'];
var loadedURL = 'page1.html';
The input to this function would be (true,'incident')
function(next,wizardname)
{
var WizSize = incidentWizard.length;
wizardName = [wizardName] + 'Wizard';
var wizardPOS = jQuery.inArray(loadedURL,incidentWizard);
And now i want to use the wizardname parameter to decide what array i am going to use...
Loader(incidentWizard[wizardPOS],true);
Ive also tried
Loader([incidentWizard][wizardPOS],true);
and
Loader([incidentWizard][wizardPOS],true);
Also the loader function just required the string value in the array at wizardPOS sorry for confusion
But when trying this i always end up with the outcome...
/incidentWizard
I know this is something to do with using computed values but i've tried reading about them and cant seem to solve this issue.
Basicly i want to use the computed value of wizardName to access an an array of that name.
Please help supports, looking forward to seeing many ways to do this!
On this line:
wizardName = [wizardName] + 'Wizard';
You are attempting to concatenate the string 'Wizard' to an Array with one string element "incident". I'm assuming you just want regular string concatenation:
wizardName = wizardName + 'Wizard';
However, now you only have a string, not an array instance. To fix that, change the way you define your *Wizard arrays to something like:
var wizardyThings = {
incidentWizard : ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then your function (which is missing a name as it stands), becomes:
function someMethod(next, wizardname) {
wizardName = wizardName + 'Wizard';
var wizSize = wizardyThings[wizardName].length;
var wizardPOS = jQuery.inArray(loadedURL, wizardyThings[wizardName]);
...
}
You can only access properties of objects that way. For global values, window[ name ] will work. For simple local variables it's just not possible at all. That is, if inside a function you've got
var something;
then there's no way to get at that variable if all you have is the string "something".
I would just put each array as a prop on an object:
var obj {
incidentWizard: ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then you can just do obj['incidentWizard'] or obj.incidentWizard this will return:
['page1.html','page2.html','page3.html']