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.
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
.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With