Check if array exists in json Javascript/Jquery - javascript

I have a json file from the twitter api.
Sometimes it does have the media[0] array and sometimes it doesnt.
If it does i want to add the array to another array so it reminds it otherwise i want it to check the next one.
this is what i tried but it didnt work fine yet.
if(twitter.statuses[key].entities.media[0].media_url!=="Uncaught TypeError: Cannot read property '0' of undefined"){
console.log(twitter.statuses[key].entities.media[0].media_url);
}
It keeps giving the error: Uncaught TypeError: Cannot read property '0' of undefined
if the media array doesnt exist otherwise it works fine and goes further.
Does someone know how to fix this?
Thanks for helping!

You're getting the error because you want to retrieve first element of ... nothing (twitter.statuses[key].entities.media[0]; media is already a null and you can't access first element of null)
Try checking with
if (typeof twitter.statuses[key].entities.media != "undefined") {
...

An undefined property has the undefined type and value, you can check against it like this:
if (twitter.statuses[key].entities.media !== undefined) {
// ...
}
or like this:
if (typeof twitter.statuses[key].entities.media !== "undefined") {
// ...
}

I suggest you to always initialize variables to check null or undefined values.
In your case:
var media0 = twitter.statuses[key].entities.media[0] || null;
if(media0 != null){
if(media0.media_url != null)
console.log(twitter.statuses[key].entities.media[0].media_url);
else
console.log('twitter.statuses[key].entities.media[0].media_url is null or not defined');
}
else
console.log('twitter.statuses[key].entities.media[0] is null or not defined');

Related

Uncaught TypeError: Cannot read property 'options' of undefined javascript

Everything works fine but from time to time there is a problem with the function. This makes it impossible to click a button and select a value from list. I tried to debug it but nothing is returned in the console.
_getSimpleProductId: function (element) {
var allOptions = element.config.options,
value = element.value,
config;
config = _.filter(allOptions, function (option) {
return option.id === value;
});
config = _.first(config);
return _.isEmpty(config) ?
undefined :
_.first(config.allowedProducts);
}
Error occurs:
Uncaught TypeError: Cannot read property 'options' of undefined
I think I have to change my question to "What I'm doing wrong?".
you should null check element.config
var allOptions = element.config ? element.config.options : null;
It looks like it's not always defined in your code
Your problem is that element.config is undefined.
You can either go with Basem's anwser (which would totally work) or find the source of the problem.
To me it looks like you expect to have options for the rest of your code, so I would go with the second solution.
Cheers!

Javascript - Check Amazon Objects to see if defined

I get an error if part of the Amazon product is missing. For example, I can do this check:
typeof success.data[i].OfferSummary[0].LowestNewPrice[0].Amount !== "undefined"
but if OfferSummary is not defined this would throw an error. Do I need to check every object under the data? Is there an easier way?
I was thinking of doing a try ... catch and trapping the error, but I'm sure someone has run into this before.
Yes you'll need to check at each step or wrap the check in a try catch block.
At the moment you're trying to access a property on undefined, which does not exist.
if (success.data[i] && success.data[i].OfferSummary[0] &&
success.data[i].OfferSummary[0].LowestNewPrice[0] &&
success.data[i].OfferSummary[0].LowestNewPrice[0].Amount !== undefined) {}
//OR
var amount = null;
try {
amount = success.data[i].OfferSummary[0].LowestNewPrice[0].Amount;
} catch( err ) {}
if (amount !== undefined){}
If you're using lodash you may use function _.get:
var amount = _.get(success, 'data[' + i + '].OfferSummary[0].LowestNewPrice[0].Amount', 0);
The 3rd parameter is default value which will be returned in case of smth in this path is not defined.
Actually, under the hood it's just a set of if-checks but the code looks more elegant.

js code to tell if a function is available for an object

The following line of javascript gets a Uncaught TypeError: Object #Text has no method 'getAttribute' in chrome and safari but not in IE.
this.Element.getAttribute("whatever")
I get that this.Element is the main problem, but would like a temporary fix for debugging other parts of the code. How can test to see if a function is available on an item without getting a javascript error?
if (this.Element.getAttribute)
{
// exists
}
else
{
// does not
}
if (this && this.Element && typeof this.Element.getAttribute == "function") {
// ...
}

Uncaught TypeError: Cannot call method 'show' of null

I am getting an :Uncaught TypeError: Cannot call method 'show' of null" error in a script which points out the error is somewhere in this area, see below:
// Show the correct more view images and if there are moreviews displayed, display the more views title
if (selectedmoreview !== null && selectedmoreview !== undefined && howMany > 0) {
selectedmoreviewtitle.show();
selectedmoreview.invoke('show');
} else {
if(howMany > 0){ selectedmoreviewtitle.hide(); }
}
spConfig.configureElement(dropdownEl);
Can anyone help me sort this out and have my functionality working? Some expert advice would be truly appreciated
Per request:
As far as I can see (and I only looked quickly) you are trying this line of code:
selectedmoreviewtitle = $('moreviews-title');
in the colorselected.js on row 204. And there's no element with id or class named 'moreviews-title'. So that's why it gets null.
Further more, you'd probably want to use class selector '.moreviews-title' or id selector '#moreviews-title'.
You check selectedmoreview, but you try to call selectedmoreviewtitle.show(). Since selectedmoreview isn't null selectedmoreviewtitle probably is.

Javascript - Cannot call method 'split' of null

I have a javascript error that occurs on my site, Im pretty sure I know why, but I dont know how to fix it!
here's the error:
Uncaught TypeError: Cannot call method 'split' of null
Here's my JS code:
$(function(e) {
if (document.cookie.indexOf("login") >= 0) {
$("a#loggedInUser").html( $.cookie("login").split("|")[0] );
}
});
I'm just trying to display the username stored in the "login" cookie. Now, im pretty sure the error is because the value returned sometimes isn't a string, then it doesn't have the split method, so it causes this error.
How can I fix that? Any ideas?
Thanks!
Well you can do something like this to set a default if the value is null.
var login = $.cookie("login") || "";
$("a#loggedInUser").html(login);
Also, if you do that you might not need the document.cookie.indexOf thing.
It's probably the case that $.cookie("login") is not returning a valid string. I think the problem is that it's possible that: document.cookie.indexOf("login") >= 0 is true but $.cookie("login") is still null or undefined. It makes sense to use the same check e.g.:
$(function(e) {
var cookie = $.cookie("login");
if(cookie) {
$("a#loggedInUser").html( cookie.split("|")[0] );
}
});
Check the length of the cookie. This way you validate two things at once.
if (document.cookie.indexOf("login") >= 0 && $.cookie("login").length) {
$("a#loggedInUser").html( $.cookie("login").split("|")[0] );
}

Categories