IF statement to identify 'null' in loop being ignored - javascript

I have the following loop which I have put together and is working (up to a point):
for (var i = 0; i < dataIn.length; i++) {
if (dataIn.YourName = [] ) {
var modifiedName = dataIn[i].YourName.replace(/ \([\s\S]*?\)/g, '');
dataIn[i].YourName = modifiedName;
}
else {
console.log('Do Nothing');
}
}
However, I run into an error when the content from the API source is empty (null).
Console error: Cannot read property 'replace' of null
As a result I have tried to update my loop to only run if the information is NOT null or undefined (see below), but it is being ignored and still trying to run.
for (var i = 0; i < dataIn.length; i++) {
if (dataIn.YourName !== null && dataIn.YourName !== '' ) {
var modifiedName = dataIn[i].YourName.replace(/ \([\s\S]*?\)/g, '');
dataIn[i].YourName = modifiedName;
}
else {
console.log('Do Nothing');
}
}
Sample data from the API.
What works:
"YourName": "John Citizen",
What throws the console error:
"YourName": null,

Let's first address an issue here. This line:
if (dataIn.YourName = [] ) {
Will always evaluate true. You are assigning an empty array to your YourName property and then using that assignment in an if - empty arrays are always truthy.
As to how you've tried to correct it, you're checking initially dataIn.YourName but then trying to read dataIn[i].YourName - you need to be consistent. I suspect what you want is:
if (dataIn[i].YourName !== null && dataIn[i].YourName !== '' ) {
var modifiedName = dataIn[i].YourName.replace(/ \([\s\S]*?\)/g, '');
dataIn[i].YourName = modifiedName;
}

Related

TypeError: Cannot read property of null

I get the error in the title even though I have tried all the solutions. About the value of null;
If my code is ;
Output: TypeError: Cannot read property of null
case '!facebook':
face.Profile(facebook, function(result) {
let like = result.profiles.like;
let comments = result.profiles.comments;
if(like === null || comments === null){
//code.
}
else {
//code.
}
});
break;
You have to verify that each child of your object exists before you reference the next level. In your case, that means testing the existence of result and then result.profiles before trying to use any of the object values in profiles. See the code below.
Without seeing the rest of your case statement or how you're setting the value of face, it's hard to tell if you're going to run into other issues.
case '!facebook':
face.Profile(facebook, function(result) {
// Set default values
let like = null;
let comments = null;
// Set values only if there's a result containing profiles
if (result && result.profiles) {
like = result.profiles.like;
comments = result.profiles.comments;
}
if (like === null || comments === null){
//code
} else {
//code
}
});
break;

JavaScript .startWith() function not working in IE, inside angularjs project

Hi im using Angularjs for my project, There is nationality search drop down. I want to map which is typing on Input and filter it inside nationality JSON object. This part is working fine in other browsers except IE. There is console error "Object doesn't support property or method 'startsWith'". this is my code, Can i know how to add "String.prototype.startsWith" for this issue for my code.
$scope.searchNationality = function (data) {
var output = [];
if (data != "" && data != undefined) {
$scope.ShowNationalityDropDown = true;
for (var i = 0; i < $scope.nationalityList.length; i++) {
if ($scope.nationalityList[i].content.toLowerCase().startsWith(data.toLowerCase())) {
output.push($scope.nationalityList[i]);
}
}
$scope.nationalityListSearchResults = output;
} else {
$scope.ShowNationalityDropDown = false;
$scope.nationalityListSearchResults = [];
}
};
You can try changing from .startsWith to .indexOf since it is compatible with IE for lower versions. If .indexOf returns 0 then the string is in the first position of the string that calls that function, which can be usable when you are in this kind of situation that you can't use .startsWith().
const str = "Hey this is a sample string!"
console.log(str.indexOf("Hey") === 0)
console.log(str.indexOf("sample") === 0)
$scope.searchNationality = function (data) {
var thereIsData = data != "" && data != undefined;
var output = thereIsData
? $scope.nationalityList.filter(function (nationality) {
return nationality.content.toLowerCase().indexOf(data.toLowerCase())) == 0;
})
: [];
$scope.ShowNationalityDropDown = thereIsData;
}

Call functions from sources directly in Chrome console?

For a website there is this function under sources with the code:
betSlipView.prototype.stakeOnKeyUp = function(_key) {
var model = ob.slip.getModel(),
defval = ob.cfg.default_bet_amount;
selector = toJqId(["#stake-", _key].join('')),
stake_box = $(selector),
spl = stake_box.val();
if(spl != defval) {
spl = ob.slip.cleanFormatedAmount(spl);
if(spl === '' || isNaN(spl)) {
spl = 0;
$(selector).val('');
}
model.setBetStake(_key, spl);
$(toJqId(['#ob-slip-estimate-', _key].join(''))).html(
model.getBet(_key, 'pretty_returns')
);
} else {
$(selector).val(defval);
model.setBetStake(_key, defval);
$(toJqId(['#ob-slip-estimate-', _key].join(''))).html(
model.getBet(_key, 'pretty_returns')
);
}
//Update bonus amount
try {
var offers = model.getBet(_key, 'offers');
}
catch(err) {
var offers = "";
}
if(offers !== "" && typeof offers['STLWIN'] !== "undefined") {
this._handleAccumulatorBonusElements(_key, offers['STLWIN']);
};
// potential returns for this bet
this.updateTotals();
};
I cannot figure out how to (if possible) call this function directly from the console. Firstly, when I try to write betSlipView in the console, it cannot be found. Consequently if I copy the code to the console to define the function, betSlipView is still not found and if I try to change the function name, there are some names in the function body that cannot be found either. I wish to call this function with certain arguments, is this possible?
The whole code can be found here https://obstatic1.danskespil.dk/static/compressed/js/ob/slip/crunched.pkg.js?ver=0305f181cb96b61490e0fd2adafa3a91

Chrome removes property value

I think I've run into a possible bug in chrome, but wondering if this is something I'm doing wrong. I am collecting data from an IndexedDb and adding this to an array BUT one property was always empty so I started debugging.
Below is my code for the onsuccess function and below that is a print screen of one of the rows from my console.log with one property marked with yellow. Notice how this exists and has a value!
On my second image which is when I "open" the object in chrome developer tools to see how it looks, I noticed that Title is undefined. What am I missing? What causes this behavior?
This exact code is working on the same site, just another page.
cursorRequest.onsuccess = function (evt) {
var cursor = evt.target.result;
if (cursor) {
var pushItem = true;
if (opts.searchCriterias && opts.searchCriterias.length > 0) {
pushItem = false;
for (var i = 0; i < opts.searchCriterias.length; i++) {
if (opts.searchCriterias[i].values.contains(cursor.key)) {
if (opts.includeKeyInResponse == true) items.push({ key: cursor.primaryKey, value: cursor.value });
else items.push(cursor.value);
}
}
}
if (pushItem) {
if (opts.includeKeyInResponse == true) items.push({ key: cursor.primaryKey, value: cursor.value });
else {
items.push(cursor.value);
}
console.log(cursor.value);
}
cursor.continue();
}
};
Title exists and have value
Title exists but is undefined (This is same as above, just expanded)

I am trying to check for undefined but it's not working

I have the following code:
$scope.$watch("pid", _.debounce(function (pid) {
var a = pid;
$scope.$apply(function (pid) {
if (typeof pid == "undefined" || pid == null || pid === "") {
$scope.pidLower = null;
$scope.pidUpper = null;
}
else if (pid.indexOf("-") > 0) {
pid = pid.split("-");
$scope.pidLower = parseInt(pid[0]);
$scope.pidUpper = parseInt(pid[1]);
}
else {
$scope.pidLower = parseInt(pid);
$scope.pidUpper = null;
}
});
}, 1000));
The very first time the code runs (when the pid field is empty) I check pid with the google development tools and it shows as "undefined". However when the code runs it does not go into the first if condition. Rather it goes to the second and gives an error saying:
TypeError: Object # has no method 'indexOf'
Can anyone tell me why it ignores the first if statement ?
Here is what I get when I use the console to check pid on the first line with an if:
console.log(typeof pid)
object
undefined
Here is what I get when I use the console to check pid on the first line with an if:
console.log(typeof pid)
object
undefined
This says that the type of pid is an object. It then says that the return value of console.log() is undefined.
It isn't going into the first if because the variable is not, as you thought, undefined.
It then fails because, whatever kind of object pid is, it isn't one with an indexOf method.
Try this:
if (!pid) {
$scope.pidLower = null;
$scope.pidUpper = null;
}
else if (pid.indexOf("-") > 0) {
pid = pid.split("-");
$scope.pidLower = parseInt(pid[0]);
$scope.pidUpper = parseInt(pid[1]);
}
else {
$scope.pidLower = parseInt(pid);
$scope.pidUpper = null;
}

Categories

Resources