How to check if some field does not exist in JavaScript - javascript

I have jQuery code like
for(var j in indivudvalbookdetails) {
if(indivudvalbookdetails[j]['status'] == "") {
...
}
}
Now there might be some items in the loop where status field won't exists, if there are such items the code in the if condition should work.

Try this:
var myElement = indivudvalbookdetails[j]['status'];
if (typeof(myElement) != 'undefined' && myElement != null)
{
// exists.
}
You can also try with JQuery like:
if ($('#elementId').length > 0) {
// exists.
}

Just check if its undefined:
if(typeof indivudvalbookdetails[j]['status'] === "undefined") {
...

Your code is comparing your variable to an empty string. But if this variable is not defined, it can’t compare it, so you can do :
if(indivudvalbookdetails[j]['status'] == undefined)
If the « status » var is defined but just empty you can do
if(indivudvalbookdetails[j]['status'] == null)

You check like this
if(!indivudvalbookdetails[j]['status'])

Related

Javascript: Uncaught TypeError: Cannot read property 'indexOf' of null

I'm populating a table with data - using fixed-data-table, which is a React.js component. However, that isn't so important at this stage.
The table has a search box where the issue stems from.
First, here's the interesting part of the code.
for (var index = 0; index < size; index++) {
if (!filterBy || filterBy == undefined) {
filteredIndexes.push(index);
}
else {
var backendInfo = this._dataList[index];
var userListMap = hostInfo.userList;
var userListArr = Object.values(userListMap);
function checkUsers(){
for (var key in userListArr) {
if (userListArr.hasOwnProperty(key) && userListArr[key].text.toLowerCase().indexOf(filterBy) !== -1) {
return true;
}
}
return false;
}
if (backendInfo.firstName.indexOf(filterBy) !== -1 || backendInfo.lastName.toLowerCase().indexOf(filterBy) !== -1 || backendInfo.countryOrigin.toLowerCase().indexOf(filterBy) !== -1
|| backendInfo.userListMap.indexOf(filterBy) !== -1) {
filteredIndexes.push(index);
}
}
}
This is rendered and the last part is throwing errors if you input something in the table, and a column returns null in the given cell.
The thing is, I can make the code work if I change the last part to ..
try {
if (backendInfo.firstName.indexOf(filterBy) !== -1 || backendInfo.lastName.toLowerCase().indexOf(filterBy) !== -1 || backendInfo.countryOrigin.toLowerCase().indexOf(filterBy) !== -1
|| backendInfo.userListMap.indexOf(filterBy) !== -1) {
filteredIndexes.push(index);
}
}
catch(err) {
console.log('Exception')
}
With the try/catch, it works 100% as intended and handles the indexOf returning null... But this can't be the way to properly handle it - I'm assuming this sort of exception handling is, well, supposed to be for rare exceptions, and shouldn't really be used on the front-end as much as the backend.
How do I handle the error in the title without using try/catch?
You are using indexOf, so make sure the values will not be undefined or null, You can solve it by putting the check on each values like this:
let {firstName, lastName, countryOrigin, userListMap} = backendInfo;
if ((firstName && firstName.indexOf(filterBy) !== -1)
|| (lastName && lastName.toLowerCase().indexOf(filterBy) !== -1)
|| (countryOrigin && countryOrigin.toLowerCase().indexOf(filterBy) !== -1)
|| (userListMap && userListMap.indexOf(filterBy) !== -1)) {
filteredIndexes.push(index);
}
or other way of solving this is, the default values you defined of these variables firstName, lastName, countryOrigin, userListMap, if they are array then it should be [], and if string then it should be ''.

how to check null in javaScript function?

I want to check null and empty id in JavaScript function,but if syntax isn't work ?
var id = "<%=Request["Id"]%>";
if (id !== "")
if (id !== null)
{var id = "<%=new Guid(Request["ID"].ToString())%>";
window.location = "/Controller/Action.aspx?Id=" + id; }
With javascript,
If you are trying to test for not-null (any value that is not explicitly NULL) this should work for you:
if( myVar !== null ) {
// your code
}
If you are only interested to test for not-empty (null value, zero number, empty string etc..) then try:
if( !myVar ) {
// your code
}
If you want to test for if a variable is defined at all (which I believe is what you are trying to achieve) then you can do it like:
if( typeof myVar !== 'undefined' ) {
// your code
}
Please let me know if it works for you.
Read into binary logic:
var id = "<%=Request["Id"]%>";
if (id !== "" && id != null) {
var id = "<%=new Guid(Request["ID"].ToString())%>";
window.location = "/Controller/Action.aspx?Id=" + id;
}
Then again, var id = "<%=Request["Id"]%>"; will never be null, only empty string, so perhaps you can drop that check altogether.

JSON fail and continue code

I am pulling json from an external website. I grab a string with this code from their JSON as I parse it:
breweryName = data.data[i].breweries[0].name;
The problem is that one of the entries in the JSON I receive does not have a value for breweries[0].name.
How Can I keep executing the code? Despite one bad entry? I tried this:
if(data.data[i].breweries[0].name === "undefined"){
breweryName = "N/A"
}
else{
breweryName = data.data[i].breweries[0].name;
}
That still fails
this first checks if there are breweries at given index i and also if there are nested elements, by checking for the size property; within the inner loop, it checks for the name property with typeof():
if(
typeof(data.data[i].breweries) !== 'undefined' &&
data.data[i].breweries.size > 0
){
/* traverse the individual entries */
data.data[i].breweries.forEach(function(v, i){
if(typeof(v.name) !== 'undefined'){
/* the element has a name property */
} else {
/* name property is absent */
}
});
}
next time please provide some sample data, that makes answering more easy.
because it might be array or object... which requires different treatment.
In JavaScript, use the typeof function
if (typeof data.data[i].breweries === "undefined" ||
typeof data.data[i].breweries[0] === "undefined" ||
typeof data.data[i].breweries[0].name === "undefined")
you may also want to include
if (data.data[i].breweries[0].name.trim() === "")
to check for names that are present, but empty.
A shortcut approach may work as well ...
breweryName = data.data[i].breweries[0].name || "N/A"

How to handle getElementById return Null

On our web application there are many pages. Some of them contain element "Ribbon.ListForm.Display.Manage.Workflows-Medium" while some pages not.
I would like to use same script to check against all pages. The script will hide the element "Ribbon.ListForm.Display.Manage", "Ribbon.ListForm.Display.Manage.Workflows-Medium" and "Ribbon.ListForm.Display.Manage.CheckOut-Large" if any.
function hideEdit() {
var edit = document.getElementById("Ribbon.ListForm.Display.Manage");
if (typeof edit !== "undefined" && edit.value == ''){edit.style.display = "none";};
var wf = document.getElementById("Ribbon.ListForm.Display.Manage.Workflows-Medium");
if (typeof wf !== "undefined" && wf.value == ''){wf.style.display = "none";};
var checkout = document.getElementById("Ribbon.ListForm.Display.Manage.CheckOut-Large");
if (typeof checkout !== "undefined" && checkout.value == ''){checkout.style.display = "none";};
}
The problem is when a page does not contain "Ribbon.ListForm.Display.Manage.Workflows-Medium" (the 2nd element) but contains "Ribbon.ListForm.Display.Manage.CheckOut-Large" (the 3rd element), the script will stop at in the middle with error [object is null or undefined]. Hence, 1st element is hided but 3rd element is not.
Could you please advice how to amend my script? Thank you.
Because getElementById() returns null if the element is not found.
element is a reference to an Element object, or null if an element
with the specified ID is not in the document.
You can just check for the truthy value instead of use the typeof test
if (edit && edit.value == ''){edit.style.display = "none";};
Demo: Fiddle
You can check like this for null element:
if (edit!=null && edit.value == '')
if (wf!=null && wf.value == '')
if (checkout!=null && checkout.value == '')
Even if the element is not existing in the page, the return type will be object and return value will be null.
so, you can check the null case also.
please see the modified code.
function hideEdit() {
var edit = document.getElementById("Ribbon.ListForm.Display.Manage");
if ( edit != null && typeof edit !== "undefined" && edit.value == ''){edit.style.display = "none";};
var wf = document.getElementById("Ribbon.ListForm.Display.Manage.Workflows-Medium");
if (wf != null && typeof wf !== "undefined" && wf.value == ''){wf.style.display = "none";}
var checkout = document.getElementById("Ribbon.ListForm.Display.Manage.CheckOut-Large");
if (checkout != null && typeof checkout !== "undefined" && checkout.value == ''){checkout.style.display = "none";}
}
thanks,
varun.
Since the question is tagged with jQuery:
$('#Ribbon\.ListForm\.Display\.Manage,#Ribbon\.ListForm\.Display\.Manage\.Workflows-Medium,#Ribbon\.ListForm\.Display\.Manage\.CheckOut-Large')
.filter(function() {
return this.value == '';
})
.hide();
First, it will select the elements you're interested in; then, it will hide those that match a simple filter based on value.

Javascript dynamic conditioning

I want to build a IF condition which is built dynamically based on the parameters it gets. More over, this is expected to be built as a plugin.
For instance, there are 3 parameters for student object, called age,name, phone_numbers. Also, there is a option object for selection parameters.
In the condition,
if(student.age >option.age & student.name == option.name & student.phonenumbers == option.phonenumbers ){
// do stuff
}
If any parameter is missing, it should not be included in the condition. For example, assume, in case option.name is undefined, then the if condition should be prepared as following,
if(student.age >option.age & student.phonenumbers == option.phonenumbers ){
// do stuff
}
Moreover, why this kind of thing is required is, here an array of (500 objects) students objects are iterated. The above condition can be splitted into seperat conditions, but then the iteration will be multipled by the number of conditions !!!. So I m looking for a way to add all conditions into one.
However, my approach is, create the expression as a string and then execute it with eval(..),but as far as I know that using eval can lead vulnerabilities.
Any one let me know a way to implement a dynamic conditions.
Note that the JavaScript and operator is &&.
For your example, this should work:
if((!student.age || student.age>option.age) &&
(!student.name || student.name==option.name) &&
(!student.phonenumbers || student.phonenumbers==option.phonenumbers)
) {
}
How about
function testStudent(student,option) {
var res = [];
var test = true;
if (student.age) res.push(student.age > option.age);
if (student.name) res.push(student.name == option.name);
if (student.phonenumbers) res.push(student.phonenumbers == option.phonenumbers);
for (var i=0;i<res.length;i++) {
test = test && res[i];
}
if (res.length > 0 && test) {
//do stuff
}
}
generic:
function testObjects(obj1,obj2) {
for (var o in obj1) { // assuming obj2 is a superset of obj1
if (o === "age" && obj1.age <= obj2.age) return false;
if (obj1.hasOwnProperty(o) && obj1[o] != obj2[o]) return false;
}
return true;
}
var ok = testObjects(student,option);
You can have your conditions in functions and those functions in an Array. so then you can do a loop in the Array and call every function (condition).
var aConds = [];
function firstCond(params) {return (params<0)};
function secondCond(params) {return(params!='hi')};
aConds.push(firstCond);
...
for(var i=0;i<aConds.length;i++)
{
if(!aConds[i](params)) console.log("a condition has not been meet");
}
Would it work to allow undefined in each condition?
if((student.age == undefined || student.age > option.age) && (student.name == undefined || student.name == option.name) ...

Categories

Resources