JavaScript proper way to handle null in JSON object - javascript

Here is the code :
for (i = 0; i < data.RecruitingGroups.length; i++) {
data.RecruitingGroups[i].id = i;
if (data.RecruitingGroups[i].Rule.Rules != null) {
for (j = 0; j < data.RecruitingGroups[i].Rule.Rules.length; i++) {
data.RecruitingGroups[i].Rule.Rules[j].id = j;
}
}
}
Problem is that sometimes RecruitingGroups[].Rule is null. So I tried to verify it was not null before continuing and running the next for loop, but it still throws the error:
Uncaught TypeError: Cannot read property 'Rules' of null
How can i bypass this error.

your second loop needs to increment j++ not i++. =)

You're testing if Rule.Rules is null. That's not the problem; Rule itself is null, as evidenced by the error message. You need to test both Rule and Rule.Rules if either can be null.
Try
if (data.RecruitingGroups[i].Rule && data.RecruitingGroups[i].Rule.Rules) {

if (data.RecruitingGroups[i].Rule && data.RecruitingGroups[i].Rule.Rules) {
for (j = 0; j < data.RecruitingGroups[i].Rule.Rules.length; i++) {
data.RecruitingGroups[i].Rule.Rules[j].id = j;
}
}

Related

TypeError: Cannot read properties of undefined (reading 'length'). Codewars task

I write solutions to tasks and got
TypeError: Cannot read properties of undefined (reading 'length').
This is my solution
function sumArray(array) {
if (array === null || array.length < 2) {
return 0;
}
let sum = 0;
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
return sum - Math.max(...array) - Math.min(...array)
}
Could you help me find an error in my code?
undefined is not === with null. You need to test for both before calling length on your argument, or don't call this method with an undefined argument.
You need to check is array even defined and that it is type array.
And I think you need to return 0 in all variant where argument array is not defined or null
if (!array || (Array.isArray(array) && array.length < 2)) {
return 0;
}
Based on the code you provided, it's possible that the error is being caused by calling the sumArray function with an undefined or null value as its argument. The code below is fixed.
function sumArray(array) {
if (!Array.isArray(array) || array.length < 2) {
return 0;
}
let sum = 0;
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
return sum - Math.max(...array) - Math.min(...array);
}

Problems sending a object key to another object (Node)

I am trying to send variable Quantity to another object that shares the same ID for Product.
(I am using MongoDB)
It even logs the result specified below but then an error happens
for (let i = 0; i < product.length; i++){
for (let j = 0; j < cartRegistry.length; j++){
if ( cartRegistry[i].ProductId === (product[j]._id.toString()) ){
console.log(product[j]._id.toString())
console.log(cartRegistry[i].ProductId, product[j]._id)
console.log('true')
}
/* console.log(quantity[i].id === product[j]._id.toString()) */
}
}
C:\Users\Toni\Documents\Aulas Node\store\routes\cart.js:22
if ( cartRegistry[i].ProductId === (product[j]._id.toString()) ){
^
TypeError: Cannot read properties of undefined (reading '_id')
at C:\Users\Toni\Documents\Aulas Node\store\routes\cart.js:22:60

Remove attributes from html string - error with removeAttributeNode

I am trying to remove all attributes except for certain whitelisted ones from a long html string. I am using the DOM to parse it.
I know there are a lot of other questions about this, but my question is specifically about the error I am getting with executing removeAttributeNode in my code below.
var div = document.createElement('div');
div.innerHTML = '<p class=\"p\">text here</p> <div id=\"divId\"></div>';
var elements = div.getElementsByTagName('*');
var whitelist = ["src", "width", "height"];
for (var i = 0; i < elements.length; i++) {
if (elements[i].attributes.length !== 0) {
var attr = elements[i].attributes;
for (var j = 0; j < attr.length; j--) {
var attrName = attr[j].name;
for (var k = 0; k < whitelist.length; k++) {
if (attrName !== whitelist[k])
elements[i].removeAttributeNode(attr);
}
}
}
}
But, I keep getting the following error: Failed to execute 'removeAttributeNode ' on Element: the 1st argument provided is either null, or an invalid Attr object.
But, I checked with console statements and elements[i] is not null. For example, elements[0] = <p class="p">. How do I get removeAttributeNode to work? Thank you for your help!
In the last loop, do something like this.
for (var k = 0; k < whitelist.length; k++) {
if (attrName !== whitelist[k])
{
elements[i].removeAttributeNode(elements[i].getAttributeNode(attrName ));
}
}

the property of the "Stub Object" object does not meet the checkpoint's condition

"the property of the "Stub Object" object does not meet the checkpoint's condition" –I got this error, I tried every type of checkpoint.
for (i = 0; i < rows; i++) {
j = 1;
cellvalue = grid.wValue(i, j);
grid.ClickCell(i, j);
//The problem is this checkpoint;
aqObject.CheckProperty(Aliases.browser.page1921681611258080.panelTabpanelBody.p‌anelGamblerpanel.panelTabpanel.panelForm.panelFormtargetel.panelContainer2.tableD‌​ isplayfield4.panelDisplayfieldInputel, "contentText", cmpEqual, "995");
}
The error you get means that the object you pass to the CheckProperty method is not found. You can check the object for existence before calling the checkpoint.
for (i = 0; i < rows; i++) {
j = 1;
cellvalue = grid.wValue(i, j);
grid.ClickCell(i, j);
var obj = Aliases.browser.page1921681611258080.panelTabpanelBody.p‌anelGamblerpanel.panelTabpanel.panelForm.panelFormtargetel.panelContainer2.tableD‌​ isplayfield4.panelDisplayfieldInputel;
//The problem is this checkpoint;
if (false == obj.Exists)
Log.Error("The object is not found");
else
aqObject.CheckProperty(, "contentText", cmpEqual, "995");
}

Javascript / jQuery + length = problem

A small version of my script would be this:
var x = null;
for(var i=0; i<x.length; i++)
{
//do stuff
}
I noticed (by doing some 'alert' debugs) that my script halts when evaluating x.length. Even when i try to print it in an alert, the script stops.
The idea is that somethimes my x variable is an array, sometimes is null.
Of course, I am a beginner, so probably i've done something stupid. No errors appear in my Firefox 6 error console.
Thanks a lot for any ideas!
try
var x = null;
for(var i = 0; x && i < x.length; i++) {
//do stuff
}
This will first check whether x is not null. If x is null, for will not run. If it is not null, for will run as usual.
In your code x is null and you are trying to get the length property from a null value which will throw a javascript error. Please check your console you will definitely see an error.
In such situations you should always make sure you do null check before accessing any property of the object or variable. Try this
var x = null;
if(x){
for(var i=0; i<x.length; i++)
{
//do stuff
}
}
That's because it's null. Add this if statement
if (x !== null){
for(var i=0; i<x.length; i++)
{
//do stuff
}
}
and it should be fine.
var x = null;
if(x !== null){
for(var i=0; i<x.length; i++)
{
//do stuff
}
}
Seems to fix the problem
Why don't you initialize x with var x = [];? This way, you can make sure that it is always an array, yet the loop won't do anything if it's empty.
You can't call the method length on a null object.
So you need to test if the object is null before calling it.
var x = null;
if(x != null)
{
for(var i=0; x!= null && i < x.length; i++)
{
//do stuff
}
}
or
var x = null;
for(var i=0;x!= null && i<x.length; i++)
{
//do stuff
}
Another option here would be to initialize x to an object with the length property -
x = {
length : 0
};
instead of
x = null;
EDIT : pulsar's answer makes more sense!

Categories