How can I add an "else" statement to the following dictionary with key/value pairs to handle any sort of ambiguity?
var inputArr = input.match(/[\d.]+/g).map(Number);
var inputAnswer = ""
inputArr.forEach(function(element, index){
var lookUp = {
"1":"611"
"2":"612"
"3":"613"
"":""
};
inputAnswer = lookUp[element];
}
return inputAnswer
});
As you can see, the key/value pairs are only programmed to handle "1","2","3", and "". How can I add another value to it which would return blank string ("") if it is passed any other value? Just want it to be dynamically set up to handle any sort of data. Thanks!
Using a simple ternary, combined with hasOwnProperty will let you do what you want.
Note: using a simple || check may not give the desired results, as it will return '' if falsey value is set in the lookUp object. For a demo of why / how this may not do what you expect, see this fiddle
var inputArr = input.match(/[\d.]+/g).map(Number);
var inputAnswer = ""
inputArr.forEach(function(element, index) {
var lookUp = {
"1":"611"
"2":"612"
"3":"613"
"":""
};
// If a defined value exists, return it, otherwise ''
inputAnswer = ( lookUp.hasOwnProperty(element) ) ? lookUp[element] : '';
}
return inputAnswer
});
Related
I've read some question but I still can't figure out how to do it
I have a url example.com/event/14aD9Uxp?p=10
Here I want to get the 14aD9Uxp and the value of p
I've tried using split('/'+'?p=') but it doesn't work
I want to use regex but I dont really understand how to use it
var URL='example.com/event/14aD9Uxp?p=10';
var arr=URL.split('/');//arr[0]='example.com'
//arr[1]='event'
//arr[2]='14aD9Uxp?p=10'
var parameter=arr[arr.length-1].split('?');//parameter[0]='14aD9Uxp'
//parameter[1]='p=10'
var p_value=parameter[1].split('=')[1];//p_value='10';
I've created a generalized function (restricted in some ways) that will return the GET value given the parameter. However this function will only work correctly provided that you do not Rewrite the URL or modify the URL GET SYNTAX.
//Suppose this is your URL "example.com/event/14aD9Uxp?p=10";
function GET(variable) {
var str = window.location.href;
str = str.split("/");
// str = [example.com, event, 14aD9Uxp?p=10]
//Get last item from array because this is usually where the GET parameter is located, then split with "?"
str = str[str.length - 1].split("?");
// str[str.length - 1] = "14aD9Uxp?p=10"
// str[str.length - 1].split("?") = [14aD9Uxp, p=10]
// If there is more than 1 GET parameter, they usually connected with Ampersand symbol (&). Assuming there is more, we need to split this into another array
str = str[1].split("&");
// Suppose this is your URL: example.com/event/14aD9Uxp?p=10&q=112&r=119
// str = [p=10, q=112, r=119]
// If there is only 1 GET parameter, this split() function will not "split" anything
//Remember, there might only be 1 GET Parameter, so lets check length of the array to be sure.
if (str.length > 1) {
// This is the case where there is more than 1 parameter, so we loop over the array and filter out the variable requested
for (var i = 0; i < str.length; i++) {
// For each "p=10" etc. split the equal sign
var param_full_str = str[i].split("=");
// param_full_str = [p, 10]
//Check if the first item in the array (your GET parameter) is equal to the parameter requested
if (param_full_str[0] == variable) {
// If it is equal, return the second item in the array, your GET parameter VALUE
return param_full_str[1];
}
}
} else {
// This is the case where there is ONLY 1 GET parameter. First convert it to a String Type because Javascript decided that str was no longer a String
// Now split it with the equal sign.
str = str.toString().split("=");
return str[1];
}
}
document.write(GET("p"));
function $_GET(param) {
var vars = {};
window.location.href.replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}
I have collected this from here:
http://www.creativejuiz.fr/blog/javascript/recuperer-parametres-get-url-javascript
It works great.
To use it just grab your parameter like:
var id = $_GET('id');
const url = new URL('http://example.com/event/14aD9Uxp?p=10');
const [,, eventId ] = url.pathname.split('/');
const p = url.searchParams.get('p');
Browser support:
https://caniuse.com/#feat=url
https://caniuse.com/#feat=urlsearchparams
Simple no-regex way
var s = "example.com/event/14aD9Uxp?p=10";
var splitByForwardSlash = s.split('/');
// To get 14aD9Uxp
splitByForwardSlash[splitByForwardSlash.length-1]
// To get p=10
splitByForwardSlash[splitByForwardSlash.length-1].split('?')[1]
I think you know how to go from here :-)
I have an object with numbers as keys and image paths as values. I am getting numbers from a combination of selected radio buttons. Such as 1111 or 2111 if the first radio buttons in each group are all selected or the second radio then all first. I want to search the object for a key of 1111 then if it exists, return its value, which would be an image path. I can successfully find if the object has a matching key, but how do I return the value for that key only? In the case of 1111 I would need to return "my/image/path1". Here is what I have so far:
var array = [];
var imgs = {
1111: "my/image/path1",
2111: "my/image/path2",
1211: "my/image/path3",
1311: "my/image/path4"
}
$(':radio').change(function() {
$(":radio:checked").each(function(i, e) {
array[i] = $(this).val();
});
var total = 0;
$.each(array,function() {
total += this;
});
matchKey = parseInt(total, 10);
// here is where I'm stuck
if (imgs contains the key matchKey)) {
console.log(value for matchKey);
}
});
You can use square-bracket notation
if (imgs[matchKey]) {
console.log(imgs[matchKey]);
}
Note: This assumes none of your values will ever be falsey (eg, 0, a blank string, false etc). Which I think is fine, as you said your values are always non-empty paths. But the warning stands. If your values could legitimately be falsy, check #Florian answer.
In your case you can use plain javascript:
if (typeof imgs[matchKey] !== "undefined") { // Check if the key exists
var value = imgs[matchKey];
}
You can use Object.keys(imgs) to retrieve an array of just the keys, and then perform a simple test to see if the key you're looking for is contained in the array:
if (Object.keys(imgs).indexOf('1111') > -1)
You can get the key-value pair by iterating through each element in array imgs using $.each
var imgs = {
1111: "my/image/path1",
2111: "my/image/path2",
1211: "my/image/path3",
1311: "my/image/path4"
}
$.each(imgs,function(key,value)
{
if(key === 1111)
return value; // This would give you the path "my/image/path1"
});
Is there a way to programmatically check whether a filter with a given name exists?
I developed a directive to process page content based on a string input, I want it to react differently in case a certain part of the string corresponds to a filter that exists in my system. For example I have a localize filter:
// Somewhere in the code
var myInput = 'localize';
// Somewhere else
var contentToProcess = 'my content';
var result = '';
if ($filter.hasOwnProperty(myInput)) // TODO: this is the part I'm trying to figure out
result = $filter(myInput)(contentToProcess);
else
result = 'something else';
Jonathan's answers is also acceptable, but I wanted to find a way to check if a filter exists without using a try catch.
You can see if a filter exists like this:
return $injector.has(filterName + 'Filter');
The 'Filter' suffix is added by angular internally, so you must remember to add it or you will always return false
Solution
This seems to work for me.
var getFilterIfExists = function(filterName){
try {
return $filter(filterName);
} catch (e){
return null;
}
};
Then you can do a simple if check on the return value.
// Somewhere in the code
var myInput = 'localize';
var filter = getFilterIfExists(myInput);
if (filter) { // Check if this is filter name or a filter string
value = filter(value);
}
Bonus
If you are looking to parse apart a filter string for example 'currency:"USD$":0' you can use the following
var value; // the value to run the filter on
// Get the filter params out using a regex
var re = /([^:]*):([^:]*):?([\s\S]+)?/;
var matches;
if ((matches = re.exec(myInput)) !== null) {
// View your result using the matches-variable.
// eg matches[0] etc.
value = $filter(matches[1])(value, matches[2], matches[3]);
}
Pull it all together
Wish there was a more elegant way of doing this with angular however there doesn't seem to be.
// Somewhere in the code
var myInput = 'localize';
var value; // the value to run the filter on
var getFilterIfExists = function(filterName){
try {
return $filter(filterName);
} catch (e){
return null;
}
};
var filter = getFilterIfExists(this.col.cellFilter);
if (filter) { // Check if this is filter name or a filter string
value = filter(value);
} else {
// Get the filter params out using a regex
// Test out this regex here https://regex101.com/r/rC5eR5/2
var re = /([^:]*):([^:]*):?([\s\S]+)?/;
var matches;
if ((matches = re.exec(myInput)) !== null) {
// View your result using the matches-variable.
// eg matches[0] etc.
value = $filter(matches[1])(value, matches[2], matches[3]);
}
}
You can just do this:
var filter = $filter(myInput);
if (filter)
result = filter(contentToProcess);
else
result = 'something else';
Undefined and null values are treated as false in JS, so this should work in your case.
This is the code:
var groups = {
"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}
I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?
Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.
You can simply filter on the given id:
groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });
This will return [{"id":"qb45657s","name":"Use me."}]
Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):
var json = '{"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}';
You would just parse it into an actual object like this:
var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in
And then search for it like:
var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].id === needle) {
needleName = jsonArray[i].name;
}
}
I'm using the following for event tracking:
var dataTrack = e.split(','); // split by comma
if (dataTrack !== undefined) {
var action = dataTrack[0];
var values = {};
values[dataTrack[1]] = dataTrack[2];
mpq.track(action, values);
}
How can I trim dataTrack[0], dataTrack[1], dataTrack[2] in a way where if any of the dataTrack vars are empty it won't break? 1 & 2 are optional...
Thanks
A common idiom in JavaScript is to provide default values like so:
// default to the empty string
var dataTrack0 = dataTrack[0] || '',
dataTrack1 = dataTrack[1] || '',
dataTrack2 = dataTrack[2] || '';
...though I think a better solution, in this case, might be to check the length of the array.
You probably want to use the length property for the array.
var dataTrack = e.split(','); // split by comma
if (dataTrack !== undefined) {
var action = dataTrack[0];
var values = {};
if(dataTrack.length > 2) {
values[dataTrack[1]] = dataTrack[2];
}
mpq.track(action, values);
}
You could add extra validation to check that dataTrack[ 1] has a length > 0 if it is possible that someone would pass "value1,,value3".
Couldn't you just check to make sure they are not empty? Also you could use the ternary operator to have a default value if they are empty (i.e. action == undefined ? "Default" : datatrack[0];).
Replace
values[dataTrack[1]] = dataTrack[2];
with
if(dataTrack.length > 2){
values[dataTrack[1]] = dataTrack[2];
}