How to fix Cannot read property hasOwnProperty of undefined - javascript

How to fix Cannot read property 'hasOwnProperty' of undefined?
Using Angular.JS 1.3
Assigning response data in $rootScope.settings in parentConroller.
so the rootScope will be like this
$rootScope.settings = api.data;
//sample
$rootScope.settings:{
"lastLogin":"2005-01-01",
"isStudent": true,
"assignedCourse": "['JAVA + DS']"
}
And accessing the $rootScope data in anotherController.JS. But here I don't want my array inside string, so to remove double quotes, I tried below ways
Attempt 1:
if($rootScope.settings.hasOwnProperty('assignedCourse')) {
$rootScope.settings.assignedCourse = ['JAVA + DS']
}
Attempt 2:
$rootScope.settings.assignedCourse = JSON.parse(rootScope.settings.assignedCourse.replace(/'/g, '"'));
// giving me Error: Unexpected token ' in JSON at position 1
Attempt 1 is working in the application, but its getting failed when i run karma debugger which is showing TypeError: Cannot read property 'hasOwnProperty' of undefined
Literally don't know how to fix this issue. Struggling to fix more than a days
I've already gone through few SO's related to my issues. but don't get any better solutions
Side Note: currently using only plain old JavaScript, not es6 or updated version.

For starters, you may want to be using angular.isDefined($rootScope.settings.assignedCourse) instead of hasOwnProperty as it is likely syntactically closer to what you are testing for (defined value instead of property ownership)
Regarding attempt 1 failing in the test, settings is undefined. You may need to re-examine your test bed and ensure your scope is being initialized as you expect.
I recreated your attempt 2 successfully, I suspect something else is going on here and may be resulting from another line.

Related

Object property in Javascript exists in the larger object but is null when accessing just that property

I'm new to JavaScript (and most coding concepts in general) and this feels like there must be some simple solution that I just haven't found yet. I need information from a property of an object (not totally sure if I'm using those terms correctly). The object is created using ArcGIS API for Javascript.
console.log(view.popup);
console.log(view.popup.id);
console.log(view.popup.title);
By logging to the console (using the lines of code shown above) I can see that the properties exist because the below lines are logged to the console (from Line 1).
id: "17e2bf83e50-widget-1"
title: "k0"
I then log just the id property (Line 2) and it prints just the id property. However, if I try to log view.popup.title (Line 3), it logs 'null' to the console. Anything else I try to print out using console.log prints the same value found within view.popup. I just need to be able to use that value stored within view.popup.title and for some reason it seems like the only one where I can see that it's there but can't access it directly?
Edit: This does certainly seem to be the issue commented on by folks below, thanks for those links! I've been trying to do stringify (as suggested in Is Chrome’s JavaScript console lazy about evaluating objects?) but finding that it only finds some of the properties. I also made an attempt at making it wait to try to find it until the property is no longer null, but it's definitely somehow later in the code where that happens (the code just enters an infinite loop until there's a call error).
View is generated using https://developers.arcgis.com/javascript/latest/api-reference/esri-views-SceneView.html#popup (which is why I don't have a full understanding of what goes into it/when and how it makes that view.popup.title property)
view = new SceneView({
viewingMode: "local",
map: scene,
container,
camera,
spatialReference: {
wkid:3089
}
});
After learning here that it's related to view.popup.title not existing yet at the point of logging it, I moved over to the ArcGIS forum to ask about how view is generated and I got an answer that lets me access it! https://community.esri.com/t5/arcgis-api-for-javascript-questions/accessing-title-of-default-popup-created-for-a/m-p/1131210#M75813
view.popup.watch("title", () => {
console.log(view.popup.title);
});

Uncaught TypeError: Cannot read property 'children' of null while running JavaScript in Chrome Console

I got this error while executing my JS code in chrome console
Uncaught TypeError: Cannot read property 'children' of null
at getFollowers (<anonymous>:98:53)
at <anonymous>:57:7
My Function being
function getFollowers(){
var followersDiv = document.querySelector('div[role="presentation"]').querySelector('li').parentElement.children;
for (var i = 0;i<followersDiv.length;i++){
var tempUser = followersDiv[i].lastElementChild.children[0].children[1];
followers.push({
userID: tempUser.children[0].textContent,
userName: tempUser.children[1].textContent,
});
}
document.querySelector('[aria-label="Close"]').click();
}
The line seems to have missing something here
var tempUser = followersDiv[i].lastElementChild.children[0].children[1];
Can someone help me with this?
I would’n say that the line you’re pointing is missing something. I would say this given line expects things to be here without providing enough guarantees.
One way or another, tempUser is built trying to use something that can be null. In my opinion, your code is quite optimistic : you assume lastElementChild to be nonEmpty, to have a children field which is a non empty array, etc… Each step after "followersDiv[i]" may lead to failure, you did not check the values’ content.
There are two strategies to make your code more robust, IMO :
Use an external library like lodash to have a more robust code. In particular, you may use _.get and _.isEmpty
Try to use a more accurate CSS selector in your querySelector as I’m not sure you need to manually browse the DOM if your selector is good enough. This way, you won’t have nodes that don’t fit your expectations.

Assertions with array -js , chai

I read this http://chaijs.com/api/bdd/
and tried to make some code with array..I need to make sure that one part of my array is including ...
expect(LoginPage.listOfItems(ITEM1).to.be.an("array")).that.include(ITEM1);
but I got
Cannot read property 'be' of undefined
when I make console.log
console.log(LoginPage.listOfItems(ITEM1).getText());
I can get proper value showed...
what i made wrong?:(
You have the brackets at the wrong place.
expect(LoginPage.listOfItems(ITEM1)).to.be.an("array").that.include(ITEM1);
You can refer the docs here

JSON return error as undefined when the value is numeric

not sure where the errors lies in what I am trying to achieve.
I am working with someone else's code and unfortunately they have used numbers for div ids in some places.
These number ids are used in various places and if I can, I want to find a way to keep things as they are.
So,
returning the following in JSON:
editorID: "1000"
And in my AJAX call i use that return like so:
var editorID = response.editorID;
CKEDITOR.instances.editorID.insertHtml('<br><img class="buildimage" src="http://www.buildsanctuary.com/phpLibs/bulletproof-master/src/userBuildImages/'+response.imageName+'"><br>');
However this gives me an error saying that the editorID is undefined.
As you can I already use a JSON response in my code, this works fine so its not a problem with datatypes etc.
I also tried to do:
alert(response.editorID);
which gave me the correct value.
When I tried putting a number directly into CKEditor insertHTML code it was showing my syntax errors so maybe thats the issue. If so, any work around for it?
Thanks. Craig.
To use a variable as a property, you have to use [] notation:
CKEDITOR.instances[editorID].insertHtml('<br><img class="buildimage" src="http://www.buildsanctuary.com/phpLibs/bulletproof-master/src/userBuildImages/'+response.imageName+'"><br>');
When you use .editorID, it's looking for a property named editorID, not 1000.
You also have to use this syntax when the property isn't a valid identifer. So if you wanted to put the number directly, you would write:
CKEDITOR.instances['1000'].insertHtml('<br><img class="buildimage" src="http://www.buildsanctuary.com/phpLibs/bulletproof-master/src/userBuildImages/'+response.imageName+'"><br>');

"SCRIPT438: Object doesn't support property or method 'url' " in IE only

I am getting the following error in IE (but not Firefox):
SCRIPT438: Object doesn't support property or method 'url'
AjaxSetup.js?version=7b8dcb65-17d1-437f-9594-0621c779427c, line 28 character 2
There are several other posts with errors like this (for other objects besides url), but all of them seem to have answers along the lines of "such a function doesn't exist in jquery" or "such a function is invalid to use in this context", and neither seems to apply to my situation at least as far as I can tell.
The function containing the line number that the error is referring to is:
function redirectToLogin() {
var redirUrl = $.url().attr("path");
if ($.url().attr("query").length > 0) {
redirUrl += "?" + $.url().attr("query");
}
top.window.location = "/Shared/Logout?redir=" + encodeURIComponent(redirUrl);
return;
}
where line 28 is the second line of the function above.
More strangely, while on the offending page (from which the above function gets called), when I type $.url() or $.url().attr("path") into the IE Developer Tools console, it returns the correct object and string, respectively. The values also seem to stay correct if I "watch" them.
Any help would be much appreciated!
EDIT:
I found a workaround:
function redirectToLogin() {
top.window.location = "/Shared/Logout?redir=" + encodeURIComponent(location.pathname + location.search);
return;
}
This seems to work and achieve the same thing, so I'm posting it in case it helps someone. However, I would still be curious to find out why the original code using jquery was not working.
I would guess if you say it works in the console that the code is trying to use it before $.url() is initialized. Is the url JavaScript included before the AjaxSetup file?

Categories

Resources