Javascript - Check Amazon Objects to see if defined - javascript

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.

Related

Cypress - nested function instead of using while loop

I spotted that when I'm using while loop, cypress does not work, so instead of while loop I found this kind of solution:
const functionName = () => {
if ( a != b ) {
this.functionName();
} else {
cy.get(".selector").click()
}
};
This block of code (typescript) works really well, but 'this' is highlighted in red and the message appears: "Object is possibly 'undefined'."
Any idea how can I to get rid off this error?
Assuming it's a typescript error, add the Non-null assertion operator
// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
// Throw exception if e is null or invalid entity
}
function processEntity(e?: Entity) {
validateEntity(e);
let s = e!.name; // Assert that e is non-null and access name
}
For reference, How to suppress "error TS2533: Object is possibly 'null' or 'undefined'" answers the same question.
You probably don't need the this. prefix at all, since the function is defined on the current scope (not a class method).

Check for undefined property in object in EJS in Node.JS

I have an object, called user, which may or may not have subproperties defined. For example, sometimes there is no "pages" object, sometimes you can go user.pages.someothervariable.
I can see in EJS how to check that user exists, but how can I check that user.pages.someothervariable exists without getting a "cannot access property of undefined" error.
I've tried this and typeof, but cannot get it to work.
<% if(locals.user.pages.pageVisits){ %>foo defined<% }else{ %>foo undefined<% } %>
I get this error:
Cannot read property 'pageVisits' of undefined
You can use short-circuiting && --
if(locals.user.pages && locals.user.pages.pageVisits) { /* do sth */ }
If user.pages is falsy, the evaluation won't proceed.
If the chain gets too long, you can try to encapsulate it into a function, like --
function getPage(user) {
return (user && user.pages && user.pages.accountPage)
|| "0"; // a fallback if the left side is falsy
}
You can check if your user has a pages field by running if(local.user.pages). This is because almost any value can be evaluated in if statements in JS. If user.pages is null, then the if statement will return false. If user.pages exists it will return true.
You could do a try-catch to avoid messiness:
var obj = {
test: "hello"
}
try {
console.log(obj.fakeKey.otherFakeKey)
}
catch(ex) {
console.log("Caught")
}

Check if array exists in json Javascript/Jquery

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');

Typescript variable "does not appear in current scope"

I am trying to use the following code:
$('body').bind('ajaxSend', function (elm, xhr, s) {
if (s.hasContent && securityToken) { // handle all verbs with content
var tokenParam = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
s.data = s.data ? [s.data, tokenParam].join("&") : tokenParam;
// ensure Content-Type header is present!
if (s.contentType !== false || options.contentType) {
xhr.setRequestHeader( "Content-Type", s.contentType);
}
}
});
I found this in the post Stack Overflow post
With typescript I get a syntax error on "options" saying "the name options does not appear in the current scope.
Can someone help and explain why I am getting this error. I see options is not declared and wonder where it comes from if it's not declared.
It's just like with JavaScript where, at run-time, any enclosing function scopes and then the global scope are searched for an options variable and if it isn't found anywhere an exception is thrown because it's not defined.
So presumably, in the example code you pulled this from, you should assume that options is defined elsewhere, and you'd need to do the same.
I believe the slight mistake is that this line:
if (s.contentType !== false || options.contentType) {
Should actually be:
if (s.contentType !== false || s.contentType) {
As your parameter s is the ajaxOptions passed to your function by jQuery.

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