Use property using the value of multiple variables - javascript

I know there's a possibility like this:
let eventSelected = "333";
let bestResult = result.personal_records[eventSelected]?.single?.best
//search like this: result.personal_records.333?.single?.best
but when I have more variables, I cannot to like this:
let eventSelected = "333";
let type = "average"
let bestResult = result.personal_records[eventSelected]?[type]?.best //error syntax
Is there some solution

For optional chaining with dynamic properties, use ?.[prop]. In this case, it would be ?.[type]?.best.

Related

Email Protected Webpage [duplicate]

I learning ES6 and try to use new for me endsWith. Before this I used includes in some of my scripts, and I thought that mechanic will be same. I picked a casual task: I have domains list and want to filter all "cn" domains. Logic is:
let ends = [".cn",".tw",".jp"]
for(let i=0;i<arrayOfDomains.length;i++){
const host = /https?:\/\/(www\.)?([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]+/.exec(arrayOfDomains[i])[0];
console.log(host.endsWith(ends))
}
and result of console.log all false. Is there a way to use array in endsWith?
No, there isn't a way to use an array in endsWith, one option is to declare another function that uses the ends array and host variable as parameters to check it.
You can try something like this:
let ends = [".cs", ".com"];
let host = "www.page.com";
let hostEndsWith = (host, ends) => {
let value = false;
value = ends.some(element => {
return host.endsWith(element);
});
console.log(value);
};
hostEndsWith(host, ends);
You can copy that code in JSFiddle to test it.
Here is the information about the endsWith function endsWith informartion
I hope this helps you!

extract sections of string with JavaScript

Suppose I have a string variable {{Name}} that looks like this:
APPLE-CARROT-PAPER-HILL
I want to create 4 variables using JavaScript that captures each piece:
var1 = APPLE
var2 = CARROT
var3 = PAPER
var4 = HILL
In Tag Manager, I assume the JS for var1 would be:
function(){
var name = {{Name}}.slice(0, {{Name}}.indexOf("-"));
return name;
}
but how then to do the others?
Not sure what You are wanting to do, but it's easier and better to:
Store all the values in one array, not separate vars.
Use split instead of complicated function to extract them.
var str = 'APPLE-CARROT-PAPER-HILL';
console.log(str.split('-'));
var name_str = "APPLE-CARROT-PAPER-HILL";
function a(){
var v1, v2, v3, v4;
var name = name_str.split('-');
[v1, v2, v3, v4] = name;
console.log(v1);
console.log(v2);
console.log(v3);
console.log(v4);
}
a();
Since you are using GTM (so far the other answers have ignored the google-tag-manager tag), I suspect your actual question is if there is a way to solve this with a single variable. Alas, no, you need to create a variable for each piece of your string
APPLE-CARROT-PAPER-HILL
// Apple
function(){
return {{Name}}.split("-")[0];
}
// Carrot
function(){
return {{Name}}.split("-")[1];
}
etc.
You can make this a bit nicer but creating a custom template that returns the value for a given index from an array, but if you want to use the parts of the name in separate fields (e.g. for use as custom dimensions) then alas you need a variable for each segment of your delimited string.
Try This,
let name = 'APPLE-CARROT-PAPER-HILL';
let nameAr = name.split('-');
let var1 = nameAr[0];
let var2 = nameAr[1];
let var3 = nameAr[2];
let var4 = nameAr[3];
I hope this code helping you
var name = "APPLE-CARROT-PAPER-HILL"
name.split("-")

Invoke method (that takes string param) on string via chaining

Can I do something like this?
var mystring = "http%3A%2F%2Fstackoverflow.com%2F";
var mydecodedstring = mystring.apply(decodeURIComponent);
I know I can do this
var mydecodedstring = decodeURIComponent(mystring);
But I'd like to chain this if possible for syntactic purposes. Just curious if it's possible. My goal is:
mystring.?????
Your should see this to see how apply works. You could do something like:
var mystring = "http%3A%2F%2Fstackoverflow.com%2F";
var mydecodedstring = decodeURIComponent.apply(null, mystring);
Clearly, apply will not provide what you are looking for.
You could define your own function on the String prototype for decoding or define it only on your object.
maybe you want to add a new method to String object?
String.prototype.apply= function(entry){
return decodeURIComponent(entry);
}
var mystring = "http%3A%2F%2Fstackoverflow.com%2F";
var mydecodedstring = mystring.apply(decodeURIComponent);

Add items to a Javascript object

My app is hitting a WebAPI that returns some JSON records. I get them via jQuery AJAX and assign the JSON to a JavaScript variable. I can loop through and make changes to existing items without issue. However, how do I add more "records" to this object? I'm trying to understand the structure of the resulting variable.
Here is what I have as a test. Is this the best way?
var trustAccounts = {"accounts":[
{"entityId":12345,
"type":"IOLTA",
"nameOnAccount":"Sam Smith Trust",
"accountNumber":"987654",
"bankCode":"003",
"bankName":"Bank of Stuff",
"accountDate":"12/15/2014",
"status":"A",
"exempt":"N",
"accountId":142922,
"action":"U"}]};
var newaccount = {};
newaccount.entityId = 23456;
newaccount.type = "IOLTA";
newaccount.nameOnAccount = "John Smith Trust";
newaccount.accountNumber = "789456";
newaccount.bankCode = "003";
newaccount.bankName = "Bank of Stuff";
newaccount.accountDate = "12/15/2014";
newaccount.status = "A";
newaccount.exempt = "N";
newaccount.accountId = 142923;
newaccount.action = "U";
trustAccounts.accounts.push(newaccount);
console.log(trustAccounts);
So if we name the returned variable object we can simply create new elements using object.newItemName. Eg below:
object.newItemName = 'Hello World'
You just add them, as if they already existed. A JSON-parsed object is just a normal JavaScript object.
let obj = {};
obj.newProp = 5;
console.log(obj.newProp); // 5
obj['newProp'] = 4;
console.log(obj.newProp); // 4
You can set them in two ways, with the dot-notation or with square brackets ([]). The dot-notation way, the value after the dot is what it's called. The square bracket can accept a string or variable, so you can use it to set a property to a specific name.
If you need to nest things, you have to create each level. For example, if you wanted to set obj.something.aValue, you could do something like this:
let obj = {};
obj.something = {};
obj.something.aValue = 5;
Or, you can also do it in fewer shots, depending what you're doing:
let obj = {
something: {
aValue = 5;
}
};

Javascript Newb : How do I instantiate a var as "blah.1" and "blah.2"?

I currently have a block like this defining some vars
var slider_1 = document.querySelector('#slider_1');
var slider_2 = document.querySelector('#slider_2');
...
And func's that take ID's like this:
function updateFromInput(id){
if(id==1){
var x = input_1.value*1;
x = Math.round((x*ratio)-offset);
slider_1.x.baseVal.value = x/scale;
}else if(id==2){
var x = input_2.value*1;
x = Math.round((x*ratio)-offset);
slider_2.x.baseVal.value = x/scale;
}
};
I am trying to refactor a bit.
I'm thinking that if I could, instead, instantiate my vars with dots rather than underscores like
var slider.1 = document.querySelector('#slider_1');
var slider.2 = document.querySelector('#slider_2');
then I'd be able to better utilize the ID already getting passed into my func's and eliminate tons of duplication.
I was hoping to simplify my funcs with something like a single call for slider.id.x.baseVal.value = x/scale; rather than having to have that code in each of the IF/ELSE conditions.
When I try that though, I get an error saying " Uncaught SyntaxError: Unexpected number ".
How should this be done?
You can't use a plain numeric key in an object.
You can do this, though:
var slider = {}; // or = [], if array syntax is more appropriate
slider[1] = ...
slider[2] = ...
Furthermore, the syntax you suggested isn't allowed if the key is actually a variable rather than a literal token.
In your example slider.id actually refers to the object with literal key id, not whatever value the variable id happens to have.
You have to put the variable inside square brackets, i.e. slider[id], so your function would be written thus:
function updateFromInput(id){
var x = +input[id].value;
x = Math.round((x*ratio)-offset);
slider[id].x.baseVal.value = x/scale;
};
You can't. The . is an invalid character for a variable identifier.
You can use it in object properties though.
var sliders = {
"slider.1": document.querySelector('#slider_1'),
"slider.2": document.querySelector('#slider_2')
};
Then use the square bracket version of the member operator to access the property.
alert( sliders["slider.1"].id );

Categories

Resources