简体   繁体   中英

Splice or Remove list of elements from JSON Array ,removing even numbered items only instead of matching items

I am having a JSON Array Output from REST API like this , I am displaying this items on the HTML using ng-repeat.

    var searchresponse = [{
"items": [{
    "employeeId": "ABC",
    "type": "D",
    "alive": "Yes"

}, {
    "employeeId": "DEF",
    "type": "D",
    "alive": "Yes"

}, {
    "employeeId": "NPK",
    "type": "D",
    "alive": "Yes"

}, {
    "employeeId": "PKN",
    "type": "A",
    "alive": "Yes"
}],
"more": false
}];

when user tries to delete using selectall/single select i am calling a REST API to remove the employee id from the db . once i get a successful response i am planning to splice / remove the values that have been selected by the user from the VIEW. I would like to remove the following employeeid and their type,alive removed from the searchresponse

    var data1=["ABC","NPK","PKN"];

I tried it doing like this

var data1=["ABC","NPK"];
var items=searchresponse[0].items;
for(i in items){
if(data1.indexOf(items[i].employeeId)!=-1){
    items.splice(i,1);
}
}
console.log(searchresponse[0].items);

What happens really is, it removed even numbered items only eg :it removed ABC,PKN . (It is removing 0th ,2nd,4th items in the list . Leaving 1st,3rd items etc).What am i missing here

The problem is when you remove the item from array, the index of other items in the array shift to the left.

Assume you have 4 items in the array( [a, b, c, d] ) and you are removing the first item so i=0 then the resulted array in the second iteration will be [b,c,d] and i will be i=1 now effectively you have missed b in the loop

 var searchresponse = [{ "items": [{ "employeeId": "ABC", "type": "D", "alive": "Yes" }, { "employeeId": "DEF", "type": "D", "alive": "Yes" }, { "employeeId": "NPK", "type": "D", "alive": "Yes" }, { "employeeId": "PKN", "type": "A", "alive": "Yes" }], "more": false }]; var data1 = ["ABC", "NPK", "PKN"]; var data1 = ["ABC", "NPK"]; var items = searchresponse[0].items; for (var i = items.length - 1; i >= 0; i--) { if (data1.indexOf(items[i].employeeId) != -1) { items.splice(i, 1); } } console.log(searchresponse[0].items); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM