error: Cannot read property 'split' of undefined - javascript

I am getting a value as a string from cookie which has multiple values stored in it.
I am separating these values with the use of the split() function, but I am getting an error continuously. Here is my code. It would be a great help if anyone can help me out with this.
var sourcez = jQuery.cookie("Source");
var mediumz = jQuery.cookie("Medium");
function utmze(eutmz) {
var utmz_val = jQuery.cookie("__utmzz");
for (var o = utmz_val, r = o.split("|"), a = 0; (a < r.length); a++) {
var t = r[a].split("=");
if (t[0] == eutmz) {
return t[1];
}
}
}

Make sure that string is not empty , null and undefined before you are performing the split action
function isValidString(input){
if(input != null && input != '' && input != undefined){
return true;
}
return false;
}
if(isValidString(input)){
input.split('=');
}

Make the following changes to avoid the error:
var sourcez = jQuery.cookie("Source");
var mediumz = jQuery.cookie("Medium");
function utmze(eutmz) {
var utmz_val = jQuery.cookie("__utmzz");
for (var o = utmz_val, r = o.split("|"), a = 0; (a < r.length); a++) {
if (typeof r[a] != "undefined") { // Checking if the variable is defined.
var t = r[a].split("=");
if (t[0] == eutmz) {
return t[1];
}
}
}
}

Related

Angular - multiselect-dropdown - TypeError: Cannot read property 'length' of undefined

counter: number = 0;
getDatatypes(){
if(this.counter == 0) {
if(this.appId != 0)
{
if(undefined != this.datatypes && this.datatypes.length)
for (let i = 0; i < this.datatypes.length; i++) {
this.applicationDataType = new ApplicationDataType(this.route.snapshot.params.id, this.datatypes[i].dataTypeId, this.datatypes[i].description, false);
let datatype = this.checkedDatatypes.find(y => y.description === this.datatypes[i].description);
if (datatype) {
this.applicationDataType.checked = true;
this.applicationDataTypes.push(this.applicationDataType);
} else {
this.applicationDataType.checked = false;
this.applicationDataTypes.push(this.applicationDataType);
}
}
} else {
for(let i = 0; i < this.datatypes.length; i++){
this.applicationDataType = new ApplicationDataType(this.route.snapshot.params.id, this.datatypes[i].dataTypeId, this.datatypes[i].description, false);
this.applicationDataTypes.push(this.applicationDataType);
}
}
this.counter ++;
}
}
The line
if(undefined != this.datatypes && this.datatypes.length)
is the one giving the TypeError: Cannot read property 'length' of undefined.
This is the console error I am getting
These errors are not visible to the user and do not affect the functionality. I have tried everything, but the datatypes in the front end multi select-dropdown just keep disappearing. I have tried initializing datatypes: Datatype[] = [], wrapping my for loop with if(this.datatypes && this.datatypes.length), and using ?. These just make the multi select-dropdown empty when running the front end.
it seems like this.datatypes is not an array or its null ,you can simply ignore this error with ? .
Please Change this to if(this.datatypes?.length>0)
Can you please try as below. initialize dataTypes array, then replace for loop with forEach as below
counter: number = 0;
datatypes = [];
getDatatypes(){
if(this.counter == 0) {
if(this.appId != 0)
{
this.datatypes.forEach(dtype => {
this.applicationDataType = new ApplicationDataType(this.route.snapshot.params.id, dtype.dataTypeId, dtype.description, false);
let datatype = this.checkedDatatypes.find(y => y.description === dtype.description);
if (datatype) {
this.applicationDataType.checked = true;
this.applicationDataTypes.push(this.applicationDataType);
} else {
this.applicationDataType.checked = false;
this.applicationDataTypes.push(this.applicationDataType);
}
})
} else {
this.datatypes.forEach(dtype => {
this.applicationDataType = new ApplicationDataType(this.route.snapshot.params.id, dtype.dataTypeId, dtype.description, false);
this.applicationDataTypes.push(this.applicationDataType);
})
}
this.counter ++;
}
}

JavaScript Check multiple variables being empty

I'm trying the following code:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array('var1','var2','var3');
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
count++;
}
}
console.log(count);
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
The result here should have been count = 2 because two of the variables are empty but it's always 0. I guess it must something when using if (field_is_empty(name)) because it might not getting the name converted to the name of the actual var.
PROBLEM 2# Still related
I've updated the code as Karthik Ganesan mentioned and it works perfectly.
Now the code is:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array(var1,var2,var3);
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
count++;
}
}
console.log(count);
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
And the problem is that if add a new if statement something like this:
if (count == '3') {
console.log('AllAreEmpty');
} else {
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
//Set the empty variables as "1900-01-01"
variableService.setValue(name,"test");
}
}
}
It does nothing and I've tested using variableService.setValue('var1',"test") and it works.
PS: The variableService.setValue is a function controlled by the software I don't know exactly what it does I know if use it like mentioned on above line it works.
In your first attempt you used the variable names as strings when you created an array. You need to either use the values themselves:
vars = new Array(var1,var2,var3);
or if you insist to use them by their names, then you need to find them by names when you use them:
if (field_is_empty(window[name])) {
It does nothing
That's not really possible. It could throw an error, or enter the if or enter the else, but doing nothing is impossible. However, since you intended to use the variables by name in the first place (probably not without a reason) and then you intend to pass a name, but it is a value and it does not work as expected, I assume that your initial array initialization was correct and the if should be fixed like this:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array(var1,var2,var3);
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var v = window[vars[i]]; //You need the value here
if (field_is_empty(v)) {
count++;
}
}
console.log(count);
if (count == '3') {
console.log('AllAreEmpty');
} else {
for (var i = 0; i < vars.length; ++i) {
var v = window[vars[i]];
if (field_is_empty(v)) {
//Set the empty variables as "1900-01-01"
variableService.setValue(vars[i],"test");
}
}
}
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
You definitely incorrectly initialize array, you put strings "var1", "var2", "var3" instead of references to strings (variables).
Try this:
vars = new Array(var1,var2,var3);
Your array is wrong
it should be
vars = new Array(var1,var2,var3);
here is the jsfiddle

Can I use the 'in' keyword to test a property in an (tree) object

Let's say I've got the following object:
Variables.settings.backend.url = 'http://localhost';
What I would do to test is url is available, is do to the following:
if ('settings' in Variables && 'backend' in Variables.settings && 'url' in Variables.settings.backend) {
// true
}
This is quite cumbersome.
If this was PHP, i could just do
if (!empty($variables['settings']['backend']['url']) {
//true
}
Can this be done any simpler in JS?
I wrote a function to test this :
var isModuleDefined = function(moduleName) {
var d = moduleName.split(".");
var md = d[0];
for (var i = 1, len = d.length; i <= len; i++) {
if (eval("typeof " + md) !== "undefined") {
md = md + "." + d[i];
continue;
}
break;
}
return i === len + 1;
};
isModuleDefined("Variables.settings.backend.url");
but i really don't know about the cost-efficiency of that method, using eval.
Edit (Without eval..):
var isModuleDefined = function(moduleName) {
var d = moduleName.split(".");
var base = window;
for (var i = 0, len = d.length; i < len; i++) {
if (typeof base[d[i]] != "undefined") {
base = base[d[i]];
continue;
}
break;
}
return i === len;
};
Yet another variant
function isFieldExist(expression){
var fields = expression.split('.'),
cur = this;
for(var i=0; i<fields.length; i++){
if(typeof cur[fields[i]] === "undefined") return false;
cur = cur[fields[i]];
}
return true;
}
for using
isFieldExist("Variables.settings.backend.url"); // find in global scope
isFieldExist.call(Variables, "settings.backend.url"); // find in Variables

Javascript undefined error on last iteration

When looping through this string, the alert prints out test 4 times (correctly) but then also prints "undefined" at the end. How do I make it doesn't return undefined.
This returns - undefinedCAFE ::
alert(match("abcdef", "CAfe"));
function match(string, pattern) {
var patternUpperCase = pattern.toUpperCase();
var stringUpperCase = string.toUpperCase();
var stringConcatenate;
var answer;
for (var i = 0; i < patternUpperCase.length; i++) {
if (patternUpperCase.charAt(i) != undefined) {
if (patternUpperCase.charAt(i) >= 'A' && patternUpperCase.charAt(i) <= 'Z') {
stringConcatenate += patternUpperCase.charAt(i);
alert("test");
}
}
}
return stringConcatenate;
}
The match function doesn't have a return statement, so it returns undefined. This means that
alert(match("abcdef","CAfe"));
will always show an alert of "undefined" at least once. To not show the alert, call the function without using alert:
match("abcdef","CAfe");
Alternatively you can make the function return something, such as stringConcatenate, which would be computed for no reason otherwise.
try this
alert(match("abcdef", "CAfe"));
function match(string, pattern) {
var patternUpperCase = pattern.toUpperCase();
var stringUpperCase = string.toUpperCase();
var stringConcatenate;
var answer;
var i = 0;
for (var i = 0; i < patternUpperCase.length; i++) {
if (patternUpperCase.charAt(i) != undefined) {
if (patternUpperCase.charAt(i) >= 'A' && patternUpperCase.charAt(i) <= 'Z') {
stringConcatenate = stringConcatenate + patternUpperCase.charAt(i);
alert("test");
}
}
}
return stringConcatenate;
}
Last "undefined" valie is result of your function:
alert(match("abcdef", "CAfe"));
http://jsfiddle.net/sava/Dw7jm/

SOAP response (XML) to JSON

I need to consume a SOAP web service which, naturally, sends its response in XML, since I'm developing a Appcelerator Titanium mobile app I would prefer the response in JSON. After looking online I converted the response using this Javascript code, it mostly worked but returned results such as the following:
{
"SOAP-ENV:Body" : {
"ns1:linkAppResponse" : {
"ns1:result" : {
#text : true;
};
"ns1:uuid" : {
#text : "a3dd915e-b4e4-43e0-a0e7-3c270e5e7aae";
};
};
};
}
Of course the colons and hashes in the caused problems so I adjusted the code to do a substring on the name and drop off anything before the ':', then a stringified the resulting JSON, removed all the hashes and parsed the JSON again. This is a bit messy for my liking but I end up with something usable.
Here is the xmlToJson code I'm using:
// Changes XML to JSON
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) {// element
// do attributes
if (xml.attributes.length > 0) {
obj["#attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["#attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) {// text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName.substring(item.nodeName.indexOf(":") + 1);
if ( typeof (obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if ( typeof (obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};
module.exports = xmlToJson;
Which results in the following JSON:
{
Body : {
linkAppResponse : {
result : {
text : true;
};
uuid : {
text : "9022d249-ea8a-47a3-883c-0f4cfc9d6494";
};
};
};
}
While this returns a JSON object I can use, I would prefer to have the resulting JSON in the following form:
{
result : true;
uuid : "9022d249-ea8a-47a3-883c-0f4cfc9d6494";
};
Mostly so it's less verbose and I can simply call json.result in order check if the query was successful instead of json.Body.linkAppResponse.result.text
Any help is greatly appreciated.
Came up with a working solution, not any less dirty but it works and returns data in the format I want.
function soapResponseToJson(xml) {
var json = xmlToJson(xml).Body;
console.debug(json);
var response = {};
for (var outterKey in json) {
if (json.hasOwnProperty(outterKey)) {
temp = json[outterKey];
for (var innerKey in temp) {
if (temp.hasOwnProperty(innerKey)) {
response[innerKey] = temp[innerKey].text;
}
}
}
}
console.debug(response);
return response;
}
// Changes XML to JSON
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) {// element
// do attributes
if (xml.attributes.length > 0) {
obj["#attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["#attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) {// text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName.substring(item.nodeName.indexOf(":") + 1).replace('#', '');
if ( typeof (obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if ( typeof (obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};
module.exports = soapResponseToJson;
console.debug(json):
{
linkAppResponse : {
result : {
text : true;
};
uuid : {
text : "e4f78c5f-1bc2-4b50-a749-19d733b9be3f";
};
};
}
console.debug(response):
{
result : true;
uuid : "e4f78c5f-1bc2-4b50-a749-19d733b9be3f";
}
I'm going to leave this question open for a while in case someone comes up with a better solution.
I feel like this is a fairly ugly solution (hope it doesn't offend you :) ).
Why don't you marshal the xml to an object and then use gson or jackson to map to json.
I don't know what framework you use, in spring for example, you can use jaxb2 to marshal and jackson or gson to transform your object to json.

Categories

Resources