문제

When i try to delete some object from columnListA with the objects present in columnListB i'm getting Error: columnListA[i] is undefined

can anyone please tell me some solution for this.

my json list is shown below:

columnListA =[ {id:"a1", value:"XYZ"},{id:"a2", value:"ABC"},{id:"a3", value:"JHI"},{id:"a4", value:"PLM"}]

columnListB =[ {id:"a1", value:"XYZ"}]

My code is this

for ( var j = 0, selLength = columnListB.length; j < selLength; j++)
{
    for ( var i = 0, nonSelLength = columnListA.length; i < nonSelLength; i++)
    {
     if (columnListA[i].id=== columnListB[j].id)
     {
       columnListA.splice(i, 1);
     }
    }
}
도움이 되었습니까?

해결책 2

Try:

for ( var j = 0; j < columnListB.length; j++)
{
    for ( var i = 0; i < columnListA.length; i++)
    {
        if (columnListA[i].id === columnListB[j].id)
        {
            columnListA.splice(i, 1);
        }
    }
}

JSFiddle

Remove nonSelLength = columnListA.length; i < nonSelLength; from loops and just define variable as less than length of the object

다른 팁

You're getting this because you're changing columnListA inplace. Since you delete an element, its length passes from 4 to 3, but you still iterate until i = 3.

I suggest creating a new array, instead of changing it inplace and risking this type of error. Example:

columnListA = columnListA.filter(function(nonSel) {
  return columnListB.some(function(sel) {
    return sel.id !== nonSel.id;
  });
});

Array#filter takes a function, and returns a new array that contains only the elements for which the function returns true.

Array#some takes a function, and returns true if the function returns true for all the elements on the array, and false otherwise.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top