conditional if for many values, better way - javascript

Is there a better way to deal with checking multiple values. It starts to get really busy when I have more than 3 choices.
if (myval=='something' || myval=='other' || myval=='third') {
}
PHP has a function called in_array() that's used like this:
in_array($myval, array('something', 'other', 'third'))
Is there something like it in js or jquery?

Jquery.inArray()

Besides $.inArray, you could use Object notation:
if (myval in {'something':1, 'other':1, 'third':1}) {
...
or
if (({'something':1, 'other':1, 'third':1}).hasOwnProperty(myval)) {
....
(Note that the 1st code won't work if the client side has modified Object.prototype.)

You can avoid iterating over the array by using some kind of a hash map:
var values = {
'something': true,
'other': true,
'third': true
};
if(values[myVal]) {
}
Does also work without jQuery ;)

a clean solution taken from the 10+ JAVASCRIPT SHORTHAND CODING TECHNIQUES:
longhand
if (myval === 'something' || myval === 'other' || myval === 'third') {
alert('hey-O');
}
shorthand
if(['something', 'other', 'third'].indexOf(myvar) !== -1) alert('hey-O');

Related

Optimize a function that ensures an object's properties does not have any of these values

I have an array of objects that represent form fields. I want to make sure that none of the elements in the array have their initial values. As in all fields need to be updated. The initial value is below. I'd like a simple function that checks each element and ensures none of these properties have the default fields.
[
{
key: 0,
name: '',
typeLabel: '',
typeValue: 0,
value: '',
}
...
]
Looking for help on improving this
collection.every((obj) => {
if (obj.key === 0) return false;
if (obj.name === '') return false;
if (obj.typeLabel === '') return false;
if (obj.typeValue === 0) return false;
if (obj.value === '') return false;
return true;
});
EDIT: Actually just thought of this
collection.every((obj) => {
const values = Object.values(obj);
return values.includes(0, '');
});
To be honest I'm not sure how much more better you can make it, it looks pretty decent to me! Any changes I'd make would be subjective changes that don't actually matter. Curious what other people will answer with though, maybe I'm missing something :)
I mean you could do this and it's arguably less if/elses and uses a named function to explain what it is doing which is maybe nicer? But meh I don't think this matters all that much:
function inputValueHasBeenSet(inputObject) {
return !!inputObject.key &&
!!inputObject.name &&
!!inputObject.typeLabel &&
!!inputObject.typeValue &&
!!inputObject.value;
}
collection.every(inputValueHasBeenSet);

Loop through multiple arrays with objects inside them in angularjs

I'm currently struggling to use a forEach method to loop over an array with multiple objects in it. I might be making a silly mistake but im not sure where im going wrong with this
I have an object with some arrays like this...
assistants array:
var assistants =
[
{
"countryCode":"US",
"cityName":"San Diego",
"geographicRegionCode":"CA"
},
{
"countryCode":"AD",
"cityName":"a",
"geographicRegionCode":null
}
]
function im using to loop through and return a value...
function validateAssistants () {
angular.forEach(assistants, function(a) {
if(a.countryCode === "US") {
return true;
}
});
}
When i am going to debug...it keeps on saying that a is not defined. Not sure what i'm doing wrong. Can someone point me in the right direction?
forEach() works like [1,2,3].forEach(callback), but the best best way, in my opinion is using some() to find if some element match, like assistants.some(o=>o.countryCode == "US").
var assistants =
[
{
"countryCode":"US",
"cityName":"San Diego",
"geographicRegionCode":"CA"
},
{
"countryCode":"AD",
"cityName":"a",
"geographicRegionCode":null
}
]
assistants.forEach((o)=>{
if(o.countryCode === "US") {
console.log(true);
}
})
console.log(assistants.some(o=>o.countryCode == "US"))//<-- best
forEach() iterates all elements, if you find the match at 0 position continues iterating till the end without need, some or for (with break), stops when find the match.

How to Combine Multiple Return Functions (JavaScript)

I am learning JavaScript so that I can implement Google Tag Manager. I have a list of paths that I would like GTM to rewrite to something friendlier like so:
function() {
return document.location.pathname.indexOf('/l/138281/2016-06-07/dy383') > -1 ? 'Test Success' : undefined;
}
function() {
return document.location.pathname.indexOf('/l/138281/2016-04-03/55z63') > -1 ? 'SPP Contact Success' : undefined;
I'm just not sure how to combine these returns into one function (I currently have about 30 URLs to rewrite). I imagine I can use if/else, but advice would be quite lovely.
--edit--
URL Path Rewrite To
/test-638-jsj /test-success
/spp-zxcv-765 /spp-contact-success
/foo-asdf-123 /foo
/foo-bar-987 /foo-bar
The return function mentioned above does this beautifully for an individual link. I just want to be able to rewrite a series of URLs in one function (or however it makes sense to do this most specifically). Hopefully that helps clarify.
Thanks!
It is always a great idea to structure your code: separate abstract functionality from the specific problem.
What you are actually doing is scannins strings for occurences of keywords and returning specific values if such a keyword has been found.
Therefore, you need a function performing the above computation and a JavaScript datastructure holding your keywords and their values (= Object):
// Return patterns[key] if any key is found in string, else return string:
function match(string, patterns) {
for (key of Object.keys(patterns)) {
if (string.indexOf(key) > -1) return patterns[key];
}
return string;
}
var patterns = {
'/l/138281/2016-06-07/dy383': 'Test Success',
'/l/138281/2016-04-03/55z63': 'SPP Contact Success'
}
console.log(match('/l/138281/2016-06-07/dy383', patterns)); // "Test Success"
console.log(match('/doesnotexist', patterns)); // "/doesnotexist"
console.log(match(document.location.pathname, patterns));

How to determine if $(this) is in array on click event

I have a set of id values in 4 arrays. Each array will be assigned a text value for an h1 and a p that I haven't put in yet. Right now I'm just trying to get it to alert if one of the images in array graphicDesign is clicked. I tried using $.inArray
DEMO
var graphicDesign = [$('#design'), $('#DD'), $('#SElogo')];
var webDesign = [$('#bootstrap'), $('#farm'), $('#pong'), $('#SE'), $('#dung')];
var programming = [$('#SE'), $('#dung'), $('#sacar')];
var other = [$('#firm')];
function categories() {
if ($.inArray(this, graphicDesign) > -1) {
alert('hello');
}
}
You should not store DOM objects in an array and try to match them with $.inArray.
Using ids or another attribute would be a better solution.
For example :
https://jsfiddle.net/1f9xd3t0/
var graphicDesign = ['design', 'DD', 'SElogo'];
function categories(id) {
if ($.inArray(id, graphicDesign) > -1) {
alert('hello');
}
}
categories('design');
You need to pass the event object to categories().
$('.portPic').click(function(e) {
// ...
categories(e);
});
function categories(e) {
console.log(e.target);
if ($.inArray(e.target, graphicDesign) > -1) {
alert('hello');
}
}
UPDATE
And maybe use id's rather than jQuery objects in your arrays.
var graphicDesign = ['design', 'DD', 'SElogo'];
Then use e.target.id in categories().
You can use typeof , here is an example.
// Objects
typeof {a:1} === 'object';
// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === 'object';
Array.indexOf() is a native function that does the same thing.
graphicDesign.indexOf(this) > -1 would be the equivalent of what you wrote.
In your usage, this is going to refer to the global object, unless you elsewhere assign this function to an object and call it as a method... But then you're trying to tell if the object you're calling it on is inside the graphicDesign array?
Here's an example of a usage that would fire the alert:
var graphicDesign = [ {} ]
graphicDesign[0].categories = function() {
if (graphicDesign.indexOf(this) > -1) {
alert('the object this method was called on is inside the graphicDesign array')
}
}
graphicDesign[0].categories()
It's unclear exactly what you're trying to accomplish, however (you mention a click detection, but there's no click handler here, etc.)... I hope this helps?
This block of $.inArray is working, but you put them in wrong place, it always returned -1, so you cannot get the alert('hello'). Please fix the overall logic.
if ($.inArray(this, graphicDesign) > -1) {
alert('hello'); }

Is there a “not in” operator in JavaScript for checking object properties?

Is there any sort of "not in" operator in JavaScript to check if a property does not exist in an object? I couldn’t find anything about this around Google or Stack Overflow. Here’s a small snippet of code I’m working on where I need this kind of functionality:
var tutorTimes = {};
$(checked).each(function(idx){
id = $(this).attr('class');
if(id in tutorTimes){}
else{
//Rest of my logic will go here
}
});
As you can see, I’d be putting everything into the else statement. It seems wrong to me to set up an if–else statement just to use the else portion.
It seems wrong to me to set up an if/else statement just to use the else portion...
Just negate your condition, and you'll get the else logic inside the if:
if (!(id in tutorTimes)) { ... }
Personally I find
if (id in tutorTimes === false) { ... }
easier to read than
if (!(id in tutorTimes)) { ... }
but both will work.
As already said by Jordão, just negate it:
if (!(id in tutorTimes)) { ... }
Note: The above test if tutorTimes has a property with the name specified in id, anywhere in the prototype chain. For example "valueOf" in tutorTimes returns true because it is defined in Object.prototype.
If you want to test if a property doesn't exist in the current object, use hasOwnProperty:
if (!tutorTimes.hasOwnProperty(id)) { ... }
Or if you might have a key that is hasOwnPropery you can use this:
if (!Object.prototype.hasOwnProperty.call(tutorTimes,id)) { ... }
Two quick possibilities:
if(!('foo' in myObj)) { ... }
or
if(myObj['foo'] === undefined) { ... }
you can set the condition to be false
if ((id in tutorTimes === false)) { ... }
if(!tutorTimes[id]){ ./*do xx */.. }

Categories