4

I have an Array of object

var Country = [];

It is something like

{
    "Name" : "IND"
    "Capital" : "Delhi"
    id : someID1
},
{
    "Name" : "USA"
    "Capital" : "WS"
    id : someID2
},
{
    "Name" : "UK"
    "Capital" : "London"
    id : someID3
}

Now I want to delete on of the element on certain condition. But it is throwing an error for more than 2 record.

My Error is : Cannot read property 'id' of undefined

My code is

remove : function(me, record, index){
    var CountryRec = this.Country;
    var CountryLen = this.Country.length;
    for(var i=0; i<CountryLen; i++){
        if(record.data.id == this.CountryRec[i].id){
            //delete this.checkRec[i];
            checkRec.splice(i,1);
        }
    }
}

This is throwing an error for more than 2 record. Please suggest me what I am doing wrong.

Satpal
  • 132,252
  • 13
  • 159
  • 168
David
  • 4,266
  • 8
  • 34
  • 69

4 Answers4

3
var CountryLen = this.Country.length; 

This condition returns 3 to you. But when you delete any element from the array, you indexes are rearranged. So for the first iteration you get an array with two elements indexed 0 and 1. And before the last iteration your get for i value 2, but your array contains one element which index is 0. So when you run record.data.id == this.CountryRec[i].id, it goes to the index 2 which is undefined.

If your id's are unique, use break.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
2

Assuming, you have unique id, then you could leave the loop after splicing with break

var CountryRec = this.Country;
var CountryLen = this.Country.length;
for (var i = 0; i < CountryLen; i++) {
    if(record.data.id == CountryRec[i].id) {
        CountryRec.splice(i, 1);
        break;
    }
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

var Country = [
{
    "Name" : "IND",
    "Capital" : "Delhi",
    'id' : 'someID1'
},
{
    "Name" : "USA",
    "Capital" : "WS",
    'id' : 'someID2'
},
{
    "Name" : "UK",
    "Capital" : "London",
    'id' : 'someID3'
}];

var CountryRec = this.Country;
var CountryLen = this.Country.length;
for(var i=0; i<CountryLen; i++){
    if('someID2' == this.CountryRec[i].id){
        console.log(this.CountryRec.splice(i,1));
        break;
    }
}
1

I'd like to add to @SurenSrapyan's answer.

The function "splice" changes the array. So if checkRec is a reference to an array, and there is another reference to same array, this could cause issues. That's because how JS handles references to objects. You will need to do proper clone when creating checkRec. There are many different ways to do an array or object clone. Read this.

So for example, if you're doing something like this:

var checkRec = myRec;

instead, do it this way:

var checkRec = some_clone_function(myRec);
evilReiko
  • 19,501
  • 24
  • 86
  • 102