简体   繁体   中英

Unable to remove element of array

Try so many ways of removing an element from array element

I have declare an array vehicleObj as such

var vehicleObj = [{
    regNo: "XX09WP", 
    model: "Ford KA", 
    repaircost: "23.89",
    typeRepair: "exhust"
}];

And here is my loop

vehicleObj.forEach(function(regNoPass,index){
   console.log(regNoPass);
   console.log("your in for each..");
   if(vehicleObj[index].regNo == regNoPass)
   {
      console.log("Magic has happen");
      vehicleObj.splice(regNoPass, 1);
   }
});

No matter what the regNoPass value is ie XX09WP it will not remove this from the array

Any ideas would be most welcome

Just change

vehicleObj.splice(regNoPass, 1);

to

vehicleObj.splice(index, 1);

because splice needs the index, not the value (or there would be no need to loop over the array to find that index).

Note that if you don't need to keep the same array object, the whole could be expressed as

vehicleObj = vehicleObj.filter(function(v){
     return v.regNo !== regNoPass;
});

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