check if JSON object exist in sessionstorage javascript - javascript

I am working on a site where some data is stored in the session. On the first page I need to check if the json object is already in the session.
This is the code that fails.
var passedTotaal = JSON.parse(sessionStorage.getItem('test totaal array'));
if(passedTotaal.hasOwnProperty('letterplaatnaam')){
//do something
}
When the JSON object exist it works else I get the following error:
Uncaught TypeError: Cannot read property 'hasOwnProperty' of null
I know this is because its empty.
I have looked at different stackoverflow questions but i couldn't find an answer
If there is any need for more information please let me know.

Try:
if(passedTotaal!=null && passedTotaal.hasOwnProperty('letterplaatnaam'))

var test = sessionStorage.getItem('test totaal array');
if (test) {
var passedTotaal = JSON.parse(test);
if(passedTotaal && passedTotaal.hasOwnProperty('letterplaatnaam')){
//do something
}
}
because getItem can return null as well

Related

uncaught error data undefined on ajax call

I'm making an ajax call (JavaScript) which generates through the show info function the data I'm retrieving. My problem is as follows: On one of the arrays some data don't have it, there are not many but there is still some. So it's displaying the first items but it stops when it can't retrieve the said array and return a:
Uncaught TypeError: info["xxxx"] is undefined.
What I'd really like is to be able to make it so it still retrieve / display the datas and says something like 'this data.[denomination][0].title is undefined or anything else'.
I tried to use the optional chaining operator '?.' but I clearly have no idea on how it works.
Here's what makes me get crazy: (it's the data["denomination"] that ruins it all)
request.addEventListener('readystatechange', function(){
if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
const backCall=JSON.parse(request.responseText);
if(backCall.count != 0){
for(let data of backCall.datas){
showInfo(data.title, data["author"][0].name, data["denomination"][0].title, data["denomination"][0].id);
}
}else if(backCall.count === 0){
noResult();
}
}
});
(just a little edit to be precise. I searched before hand and even looked up to the advised subjects from Stack when I was writing this)
Check if both properties exist in the object and then call your showinfo function, it should not fail
for (let data of backCall.datas) {
if (data["author"] && data["denomination"]) {
showInfo(data.title, data["author"][0].name, data["denomination"][0].title, data["denomination"][0].id);
}
}

Check if json object is undefined in Node.js

I'm getting this error "TypeError: Cannot read property '0' of undefined" when I want to extract a data from JSON file.
However, the data I want to extract is not available every time I request a JSON file, therefore, I'm getting this error which makes my Node.js Application to crash every time I'm getting this error.
simply check if it exists or not:
if (json && json['Name'] && json['Name']['Nationality']) {
data = json['Name']['Nationality'][0];
} else {
// no data, do whatever error handling you want here
}
A solution for this sort of problem is using try-catch:
try {
data = json['Name']['Nationality'][0];
} catch (error) {
data = "Sorry no data found"
}
The try function is going to run the code if it did find any error it will pass it to catch.

Querying for local storage entry without throwing errors

Working on a chrome extension. I am using the following to save some data to my local storage:
chrome.storage.local.set({ [variablyNamedEntry]: someObjectToBeSaved });
Elsewhere in my code I want to query if the entry exists and if it does, I will want to local some variable "myVar" with the object.
If the entry exists, this code works to achieve my goals:
chrome.storage.local.get(null, function(result){
myVar = result[variablyNamedEntry];
}
But if no entry exists for "variablyNamedEntry" it throws an error. I could manage this error with a try/catch sequence. But that can't be the best approach, given that I know that it will not find the entry a very large percentage of the time.
How can I achieve my goal?
Update:
I tried using:
chrome.storage.local.get([variablyNamedEntry], function(result){
if (result != undefined)
myVar = result[variablyNamedEntry];
}
But I still get the following error if the entry does not exist:
extensions::uncaught_exception_handler:8 Error in response to storage.get: TypeError: Cannot read property 'someProperty' of undefined
Please be aware the items parameter for the callback of chrome.storage.local.get is always an object and would never be undefined.
Assuming you have a key-value in which key is 'Sample-Key', you could use the following code
chrome.storage.local.get(null, function(result){
if(typeof result['Sample-Key'] !== 'undefined') {
console.log(result['Sample-Key']);
}
});
Or
chrome.storage.local.get('Sample-Key', function(result){
if(typeof result['Sample-Key'] !== 'undefined') {
console.log(result['Sample-Key']);
}
});

Detect error in javascript (in code) and act accordingly

I have some var data which might have a data[0].substring(1)[1] or it might won't (regarding the .substring())
I can't change the data I receive, neither does it come in a specified format. Please don't ask about it, the idea of this question is precisely to answer in this scenario.
I tried to do this
if(data[0].substring(1)[1]){
}
but it fails anyway with Cannot read property 'substring' of undefined so now I'm in doubt on how I should do this.
Is this possible? Is there a workaround?
You should check whether data[0] exists before trying to access it:
if(data[0] && data[0].substring(..)) {
...
}
Use try/catch/finally:
var txt;
try{
txt=data[0].substring(1)[1];
}
catch(e){
console.log(e);
console.log("The variable does not contain this data."); // at your own choice
}
finally{
if(txt!=undefined){
// do stuff with txt
}
}

Appending data to an element works but then I can't retrieve it

I'm attaching response data to the target of a jquery plugin when a preload option is set. It all seems to work a charm except the data I set is inaccessible. When I log $(elm).data(); I can see that the object was returned with the appropriate data set to the appropriate key. But when I try console.log($(elm).data('key')); I get undefined. I also get undefined when I try var elmData = $(elm).data(); console.dir(elmData.key);. So I'm logging the object on one line, seeing it in the console, trying to access a property I just confirmed exists and getting undefined.
Here is my function:
this.preloadData = function(folders)
{
var getString;
for(var folder in folders ){
getString = 'folder='+folders[folder]+'&uri='+uri+'&thumbSide='+options.thumbSide;
$.get(options.handler, getString,
function(response, serverStat, xhr)
{
$self.data(folder, response);
});
}//for
var $selfData = $self.data();
console.log($selfData);//Object{ editorial : "data", testingdata : 'some meaningless words'}
console.log($self.data());//Object{ editorial : "data", testingdata : 'some meaningless words'}
console.log($self.data.editorial);//undefined
console.dir($self.data('editorial'));//undefined
console.log($selfData['editorial']);//undefined
console.log($selfData.editorial);//undefined
$self.data('testingdata', 'some meaningless words');
console.log($self.data());//Object{ editorial : "data", testingdata : 'some meaningless words'}
console.log($self.data('testingdata'));//'some meaningless words'
}
I know the namespacing is too simple, I just tried to cut out as many factors as I could to try and understand why this isn't working. I'm developing in chrome but I've tried it in firefox also and get the same.
-----------------------------EDIT------------------------------------------
I understand what the problem is now. The console reflects all changes to an object that get made regardless of if they were made when the object was logged. So when I logged the object the property didn't exist yet because the response had yet to come back from the server, but the log still shows the property as existing because at some later point in the script execution it DID exist. Because primitive values aren't logged in the same way, the call to log the property shows up as undefined because it WAS undefined. If I refer to the property some seconds later, say on a click event it is defined(which is how I intended it to work anyway). I just got really caught up in debugging this function before I actually implemented it.
Can you do this?
$self.data['editorial']
try
console.log($self.data.editorial);

Categories

Resources