Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

id is undefined when removing an element from an array

Tags:

javascript

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.

like image 344
David Avatar asked Mar 08 '23 02:03

David


2 Answers

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.

like image 150
Suren Srapyan Avatar answered Mar 19 '23 01:03

Suren Srapyan


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;
    }
}
like image 44
Nina Scholz Avatar answered Mar 19 '23 01:03

Nina Scholz