Ignore javascript errors like in php [duplicate] - javascript

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 2 years ago.
I'm parsing some JSON with jQuery into array.
So there is a place where i'm assigning this:
$("#address_text").text(data['account']['address']['text']);
The problem is that sometimes i don't have this in the JSON and i've got error:
TypeError: null is not an object (evaluating 'data['account']['address']')
And the script is blocked under that line.
Is there anyway that i can ignore the error and assign nothing to #address_text ?
I search something like "#" sign in php. That no matter what is the error, just ignoring it.

First: If you have an error, fix the error not ignore it.
Second: Check if value exist before get the property
if (data && data['account'] && data['account']['address'] && data['account']['address']['text']) {
....
}

How about this?
if(data && data.account && data.account.address && data.account.address.text){
$("#address_text").text(data['account']['address']['text']);
}else{
$("#address_text").text("data is not valid");
}

Related

How to add null check for values returning from localStorage [duplicate]

This question already has answers here:
How to check whether a Storage item is set?
(17 answers)
Closed 2 years ago.
I have a localStorage value, which I am getting
const marks = JSON.parse(localstorage.getItem('mark'))
Now I am trying to make it robust so that if there is no key with mark in localStorage then it should not break.
localstorage.getItem('mark') ? JSON.parse(localstorage.getItem('mark')) : []
So is there any another way through which I can do the null check ?
try:
localstorage.getItem('mark') === null ? [] : JSON.parse(localstorage.getItem('mark'))
EDIT
Of course, It means:
if(localstorage.getItem('mark') === null){
return '[]'
}else {
JSON.parse(localstorage.getItem('mark'))
}
If item named mark is not null it will parse to JSON and u will get the result

Avoid an error from an undefined input-field in javascript [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 4 years ago.
I have an input-field in my form which sometimes gets displayed and sometimes not. When the input-field doesn´t get displayed and the form is about to get sent the script throws an error:
Cannot read property 'value' of undefined
I tried to catch that with this code:
if (typeof document.forms["add-new-job"].addjob_companyselect.value !== 'undefined') {
// do something
}
But the same error comes again on this line. How can I skip an undefined field?
var addNewJobElement = document.forms["add-new-job"].addjob_companyselect;
if (addNewJobElement && addNewJobElement.value) {
// do something
}

issue with output of json file caused by blank in the javascript [duplicate]

This question already has answers here:
How can I access a JavaScript object which has spaces in the object's key?
(4 answers)
Closed 6 years ago.
I need to get some data out of a json file. The issue I have in the output there is a blank in the column header. I already tried to replace the blenk with a "_" but this did not help. When I simply name it as it is I am getting the error:
SyntaxError: Expected token '}' file:
Can you tell me how I need to manipulate the script to get the Data?
{
tableData.push({
"id" : id_temp,
"datetime": feat[j].datetime,
"Percent_Available_Memory": feat[j].Percent Available Memory,
"Available_Memory": feat[j].Available_Memory,
"Total_Memory": feat[j].Total Memory,
"coverage": feat[j].coverage
});
}
OK, try this:
"Percent_Available_Memory": feat[j]["Percent Available Memory"],
...
"Total_Memory": feat[j]["Total Memory"],

object.valueOf() if returns false [duplicate]

This question already has an answer here:
Why do my MongooseJS ObjectIds fail the equality test?
(1 answer)
Closed 7 years ago.
I am baffled as to how if classes in JavaScript work, I've always known it's slightly more complicated but now I just have no idea. Code and output below.
The following json's are stored in mongodb. I'm suspecting this might be where the error is..
console.log(JSON.stringify(user)):
{"_id":"5687f787f8ad41175fab5bd5","pic":"karl.png","language":"5687f787f8ad41175fab5bd2","cell":1,"local":{"email":"karl.morrison#email.com","password":"12345"},"profile":{"name":"Karl Morrison"},"sessions":[{"id":"5687f79bf8ad41175fab5bd9","seen":false,"active":false}]}
console.log(JSON.stringify(message)):
{"authorId":"5687f787f8ad41175fab5bd5","upvotes":0,"created":"2016-01-02T16:15:23.621Z","message":"<p>aa</p>"}
Ze code:
console.log('"' + user._id.valueOf() + '" "' + message.authorId.valueOf() + '"');
console.log({}.toString.call(user._id).split(' ')[1].slice(0, -1).toLowerCase());
console.log({}.toString.call(message.authorId).split(' ')[1].slice(0, -1).toLowerCase());
if (user._id.valueOf() == message.authorId.valueOf()) {
console.log('TRUE');
} else {
console.log('FALSE');
}
Console:
"5687f787f8ad41175fab5bd5" "5687f787f8ad41175fab5bd5"
object
object
FALSE
I don't understand why TRUE isn't returned?
According to mongodb documentation:
Changed in version 2.2: In previous versions ObjectId.valueOf()
returns the ObjectId() object.
Since user._id and message.authorId are ObjectId objects the regular == compares their references thus you get false.
Try using either:
user._id.toString() == message.authorId.toString()
user._id.equals(message.authorId)
upgrading to newer mongodb driver.

Comparing variable to empty jquery object in if condition [duplicate]

This question already has answers here:
How do you check if a selector matches something in jQuery? [duplicate]
(11 answers)
Closed 9 years ago.
In the jQuery accordion API, it says "If the accordion is collapsing, ui.newHeader and ui.newPanel will be empty jQuery objects."
How can I check if ui.newheader is an empty jQuery object? I've tried it like this:
if ($(ui.newHeader) == null)
{
...
}
,like this:
if (ui.newHeader == null)
{
...
}
and this:
if ($(ui.newHeader) == "")
{
...
}
So basically, this is a question about jquery/javascript syntax :) Thanks
What you want is to know if there is 0 element in the set. Do it like this :
if ($(ui.newHeader).length==0) {
if (!$(ui.newHeader).length)
or
if (!$(ui.newHeader)[0])
jQuery object is array like collection. So, it is empty means, it's length property is 0.
if(!$(ui.newHeader).length) {...}

Categories

Resources