How to Check the variable value is [""] in JavaScript - javascript

Example:
When I check a variable containing this value [""] it returns false.
var th=[]
th.push("");
if($("#multiselect").val()==th)
It returns always false.
Thank you.
Edit 1:
changed Var to var. It was a typo.
Edit 2:
Actually, the problem I faced was I was trying to get the value from a multi-select input. The multi-select input sometimes returns values as [""] even I haven't selected any values basically it's a plugin. So I was confused and I thought [""] is a fixed primitive value like 1, 10, "bla blah",.. So I tried to compare it with the same array as the right-hand side of the '=' operator.
It was stupid. Now I posted the solution to my problem and I explained my stupidity.

there are two things:
Change Var to var
You can use includes method of Array as:
var th = [] <==== chnage Var to var
th.push("");
if(th.includes($("#multiselect").val())) { <=== you can use includes method of array
// DO whatever you want
}

Make sure var is lowercased.
You are accessing th as an array, so you’ll need to specify the index of the value you are checking: th[0]
Use triple equals, too: .val()===th[0]
Double check the jquery docs if you’re still running into trouble.
Happy coding!

A couple of things to consider:
You have a typo in the code above; var is valid; Var is invalid.
Browser will aptly complain to solve this typo.
You are comparing an array to DOM value; this will always be false.
DOM is a costly process. Unless the value associated is dynamic, its better to read once, store value into a variable and continue processing instead of reading from DOM always.
You could choose to try something on these lines:
let arr = [1,2,3,4];
let domValue = $("#multiselect").val();
arr.push(5);
arr.map((el, ix) => {
if el === domValue return true; //or choose to do something else here.
});

var th=[]; //It is var not Var
th.push("");
if($("#multiselect").val()==th[0]) // change th to th[0]

I am unable to comment so having to use an answer for now. Are you trying to check if an array has any values? If so you can use
if(th.length){
// do something
}
If you want to check a normal variable for empty string you can simply use
if(th == “”){
//do something
}

I found the solution after a couple of days when I posted this question. Now I can feel how stupid this question was.
Anyway, I'm answering this question so it might help others.
Answer to my question:
When two non-primitive datatype objects(which is the Array here) are compared using an assignment operator, it compares its reference of the object. So the object creation of both arrays would be different. If I want to check the array has [""] value, I should do something like the below.
function isArrValEmptyCheck(value) {
return !value || !(value instanceof Array) || value.length == 0 || value.length == 1 && value[0] == '';
}
console.log(isArrValEmptyCheck([""]));//returns true
console.log(isArrValEmptyCheck(["value1"]));//returns false
Sorry for the late response. Thanks to everyone who tried to help me.

Related

Type of this is always object while checking for a valid Javascrip Object

I wrote a Prototype function in javascript to determine whether an entity is a valid Javascript object or not. Something like following
// Check if Object is Valid & Have at least one element
Object.prototype._isValidObject = function () {
return this && typeof this === 'object' && !Array.isArray(this) && Object.keys(this).length >= 1;
};
The problem is it is returning TRUE for most of the values, like even for string, cause this is treated like an object for any value, like arrays, strings or json etc. There may be other ways to do this, but I need to make a prototype function for this. Please determine the correct way to Determine whether a value is a valid Javascript object having atleast one item. Thanks
EDIT
By Valid Javascript / JSON Object I mean something like this:
{
id:100,
name:'somename',
email:'maiL#mail.com'
}
To be more precise following is what I want:
const j = {id:100,name:'somename', email:'maiL#mail.com'};
const s = "{id:100, name:'somename', email:'maiL#mail.com'}";
j._isValidObject(); // Should return true
s._isValidObject(); // Should return false
const j is valid for me cause it is an object having key-value pairs. const s is invalid for me cause it's a string representation of an object, not the object itself. const s can be converted to valid Object like const j, but right now const s is just a string.
EDIT
I have found a solution, and posted it in answers. Though I am not marking it as accepted answer since I'm not sure whether it's the best way to do it. If somebody has a better solution, please post it. Thanks
I have found a solution, though I am not marking as accepted answer since I'm not sure whether it's the best way to do it. If somebody has a better solution, please post it. Thanks
// Check if Object is Valid & Have at least one element
Object.prototype._isValidObject = function () {
return this
&& !(this instanceof String)
&& !Array.isArray(this)
&& Object.keys(this).length >= 1;
};

How do I check if the members of a json array is empty, in this scenario?

I'm terribly new to javascript and I tried to foreach through members of an array to see if they are empty, but couldn't quite figure out how to do it, I've tried several ways already.
So here is the json array:
var myArray = {
a:document.getElementById('id').value,
b:document.getElementById('password').value,
};
and here is my attempt at checking if respective members of that array is empty:
for (var check in myArray) {
if((check == null)||(check.length===0)||(check=='')){
console.log("empty member found!");
break;
}else{console.log(check);}
}
as it turned out it passes the check every time and when it prints out check, it prints out only a, b in the browser console, not its value as I had expected.
I know I must've made several entry-level mistake but how should I fix it?
So as CertainPerformance pointed out, you can't really use:
if((check == null)||(check.length===0)||(check==''))
instead, I used:
if((emptyCheckArray[check] == null)||(emptyCheckArray[check].length===0)||(emptyCheckArray[check]==''))
and it did the trick! Note that my code may be redundant, but hey, safe > sorry!

How to select first of several items in JSON that exists?

JSON files are compromised of a series of key's and values. I know the potential key's in a given JSON, but not whether or not they have corresponding non-empty values. I have loaded the JSON file into an object called JSON. I want to find the first of several possible key's with a value and then assign that value to a variable. When I say "first" I mean "first" according to a priority list that is not related to the structure of the JSON:
I could do the following and it works:
if(json.age)
myValue = json.age;
else if(json.classYear)
myValue = json.classYear;
else if(json.seniority)
myValue = json.seniority
else
myValue = false;
This works but sucks for several reasons:
It is slow to write
It is annoying to rewrite the key value name each twice in each row
It is a little hard to read
It is very difficult to reason with programatically. I don't have a use case that requires this, but I can imagine wanting to arbitrarily change the order of priority from within my code.
While not terribly slow to process, I can imagine that some other approach may compute faster.
These reasons lead me to believe that the method listed above is not ideal. Is there some other pattern that would be better?
(Note: I recognize that this question borders on a "how best to" as opposed to "how to" phrasing. I know SO is not wild about that sort of question and I don't mean my question to be interpreted as such. Rather, my question should be interpreted as asking, "is there some design pattern that is particularly suited for the problem describe above?)
(Note: I will only accept a vanilla answer, but feel free to provide other answers if you believe they will be helpful).
You could use short-circuit evaluation. You'll still have to write out all of the property names, but I'm not sure there's a way to accomplish this task without doing that.
const myValue = json.age || json.classYear || json.senority || false;
Okay, so if you have a one-dimensional hash table and an array for the priority of keys, then you can use an algorithm like this to select the first one available:
function grab(hash, keyPriority) {
var value;
keyPriority.some(function (key) {
if (hash.hasOwnProperty(key)) { // check if the property exists
value = hash[key];
return true; // break out of loop
}
});
return value;
}
usage:
grab({ c: 3, d: 4 }, ['a', 'b', 'c', 'd']) // 3
You can modify this to work by truthy values, or undefined/null by changing hash.hasOwnProperty(key) to hash[key] or hash[key] != null respectively.
If you are fine with using a bit of JQuery then the following code snippet should do the job I guess.
$.each(JSONObj, function(key, value){
if (!(value === "" || value === null)){
myValue = value;
return false; //to break the loop once a valid value is found
}
});
This will assign the first valid value to your variable myValue and will also exit the loop once a valid value is found.

javascript: setting default value with IF statement instead of OR

I'm only sharing a small bit of code because there is so much going on, and I hope this is enough to answer my question.
I have some existing JS where a value is determined with an OR statement and I think I need to convert that to an IF statement. The final output is currently giving me both values if they both exist, and I only want "question" where both "question" and "name" values exist.
var question = new fq.Question(questionData.answerId, topicId,
questionData['question'] || questionData['name'],
questionData['text']);
Instead of using the OR operator (answerData['question'] || answerData['name']), I'd like to do something similar to the following:
if (questionData['question'] is undefined) {
use questionData['question'];
} else {
use instead questionData['name']
}
But, I don't know how I might accomplish such a statement within the () in the existing code pasted above. The name variable/value is always present, so there's no risk in defaulting to that. Question is only defined some of the time. And I don't ever want both appearing.
This is probably outside of the scope of my query here, but to fill in a little more detail, this code eventually outputs JSON files for topics and questions. Topics only have names values, and questions have both names and questions, but I only want the questions json to include questions values, not names. I'm pretty sure this is the key part in all of the JS to determin
Create a function and get value from there.
Need to remember scope of function:
Example Snippet:
var that = this;
var question = new fq.Question(questionData.answerId, topicId,
that.getValue(),
questionData['text']);
function getValue() {
if (questionData['question']) { //null and undefined both are false
return questionData['question']
} else {
return questionData['name']
}
}

If statement throwing error for nonexistent object

The answer to this question seems like it would be obvious, but I'm always looking to improve my semantics, so bear with me.
I have an array structure with individual items containing X,Y coordinates
var example = new Array();
example.push({x:0,y:0});
In my code I have a set interval that updates my canvas and checks for certain conditions. Including one similar to this
if(example[0].x == other.x && example[0].y == other.y)
{
//do something
}
The issue is that the array is very dynamic, and when the code is first executed the example array is empty. Hence, Chrome throws errors along the lines of "Cannot get property x". To shut up the console, I added a dummy item to the array {x:"~", y:"~"} but it seems really unintuitive. Have I implemented an undesirable data structure? What's a simple way to handle if statements for objects that... don't exist?
Why don't you just check whether the array has elements?
if (example.length && ...)
Or whether the first element is true:
if (example[0] && ...)
if (0 in example
&& example[0].x == other.x && example[0].y == other.y) {
// do something
}
(This works for arbitrary index, not just 0; if you just want to check if the array is non-empty, example.length as shown by melpomene is good.)
You should be able to check on the first-level element (i.e. 'example') - JavaScript usually throws errors like this when you try to access a property of an element that is null or undefined. Like some others have already shown:
if(example[0] && example[0].x === other.x)
The point is though that JavaScript will let you have example[0] and return as you like, but once you try to access that property, you're out of luck:
var example = [];
//undefined
example
//[]
example[0]
//undefined <--- this is a falsy value, will evaluate false in a check
example[0].x
//TypeError: Cannot read property 'x' of undefined

Categories

Resources