Mitali Kaushal Mitali Kaushal - 3 years ago 185
Javascript Question

Unable to delete an array element using splice in jQuery $.each loop

Hi I have an object which has only one property as "contacts" and its value is an array which contains 4 objects and each object has properties like email, firstname etc...

I want to remove a particular object from that array by matching its email property with an given email.

I am trying to iterate through that array using $.each loop in jQuery and trying to match email in each iteration and when matched I am trying to delete that object using splice but it is not working.

Below is a sample code similar to what I am implementing:

//main object with all the data
var data = {
"contacts": [
{
"email": "jonas.sultani@hellyhansen.com",
"firstname": "Jonas",
"lastname": "Sultani",
"prefix": "Mr",
"title": "Consultant",
"company": "Helly Hansen",
"phone": "+49 6245 99334",
"fax": "+49 6245 99335"
},
{
"email": "james.simmons@boeing.com",
"firstname": "James H",
"lastname": "Simmons",
"prefix": "Mr",
"title": "AP Lead",
"company": "Boeing",
"phone": "+1 112-445-6684",
"fax": ""
},
{
"email": "slmarino@boehringer-ingelheim.com",
"firstname": "Stephanie",
"lastname": "Marino",
"prefix": "Mrs",
"title": "Project Manager",
"company": "Boehringer Ingelheim",
"phone": "+1 650-554-5124",
"fax": ""
}
]
}

//extracting array from the data object
var myArray = data.contacts;

//sample email to match and delete the object
var email = "jonas.sultani@hellyhansen.com";

//function to delete the object containing the passed email
function deleteElement(myId){

//iterating the myArray to check the email with the given email
$.each(myArray, function(key, val){

var email = val.email;

//if the email is matched the particular object on the current index in the array is deleted using splice
if(myId === email){
myArray.splice(key,1);
return;
}
});
}

//calling the function and passing the email to delete the object
deleteElement(email);

//printing the modified array
console.log(myArray);


This method is not working so can you please let me know how can I make this work.

Note: I don't want to modify anything with the data object or myArray but I want to find solution with the current situation

Big Thanks

Answer Source

Use a do..while loop or while loop to remove elements from an array within a loop

let i = 0;

let len = data.contacts.length;

do {
  var email = data.contact[i].email;
  if (myId === email) {
    data.contacts.splice(i, 1);
    break;
  }
  ++i;
} while (i < len);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download