If condition in for loop is not working using javascript

sravanig231
Participant III

I am trying to use if condition in for loop. But it is not working at conditional level

var CodeResponse = context.getVariable('AllCodeData');

var JSONDATA = JSON.parse(CodeResponse);
var Codes = JSONDATA[0].CODE; 
context.setVariable('Code',Codes); // I am able to see code data
var flag1 = JSONDATA[1].FLAG;
context.setVariable('Flag',flag1); // I am able to see flag value
for(var i = 0; i<=JSONDATA.length; i++)
{
  for(var j = 1; j<=JSONDATA.length; j++)
  {
    if (JSONDATA[i].FLAG == "N" && JSONDATA[j].FLAG == "N" && (JSONDATA[i].CODE === JSONDATA[j].CODE)) // I am not able read flag and code data into if condition
    { 
      delete JSONDATA[i];
    }
  }
}
context.setVariable('CodeInfo', JSON.stringify(JSONDATA));

Data in AllCodeData :
[
{ "CODE": 1500, "FLAG": "N" },
{ "CODE": 1500, "FLAG": "Y" },
{ "CODE": 1500, "FLAG": "Y" }
]
While testing the above code I am getting below error
{ "fault": { "faultstring": "Execution of code failed with error: Javascript runtime error: \"TypeError: Cannot read property \"FLAG\" from undefined. (code.js:15)\"", "detail": { "errorcode": "steps.javascript.ScriptExecutionFailed" } } }
Can anyone please help me on this

Thanks,

Lakshmi.

0 4 892
4 REPLIES 4

Not applicable

the loop try

i <

and

j <

instead of <=

because, when it's 3 it's undefined.

you have only 0,1, 2 values of array. 3 is outside the array index.

This is due to you modifying a data structure as you're iterating over it. Once you `delete JSONDATA[i]` when the `if` statement is truthy, you're modifying the array being iterated over. This is a bad programming practice.

Use splice() instead of delete() and you need to decrease the length of the array inside if loop

Rather than ask people to review your code, maybe you could explain what you're really trying to do. What are you solving for? Give us an example of BEFORE data and AFTER data and explain the changes you want to make and why.