Id undefined when removing an item from an array

I have an array of objects

var Country = [];

This 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 remove an item from a specific condition. But this is a mistake for more than two entries.

My mistake: Unable to read the 'id' property from undefined

My code

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 a mistake for more than two entries. Please suggest me what I am doing wrong.

+4
source share
4 answers

Assuming you have a unique identifier, you can 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;
    }
}
+2
source
var CountryLen = this.Country.length; 

3. - , . , , 0 1. i 2, , 0. record.data.id == this.CountryRec[i].id 2, undefined.

, break.

+3

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;
    }
}
Hide result
+1

@SurenSrapyan.

"" . , checkRec , , . , JS . checkRec . . .

So, for example, if you are doing something like this:

var checkRec = myRec;

do it like this:

var checkRec = some_clone_function(myRec);
+1
source

Source: https://habr.com/ru/post/1685427/


All Articles