简体   繁体   中英

Using a for loop to delete an object from an array without affecting the rest of the array

I need to delete an employee from an array. I need to remove the full object for that employee (all of the key value pairs) with a function that will loop through the array and check for the key value firstName and delete the object based on the name.

Lets say the name is "Mike".

I want to use the splice command and a for loop. this is what I have currently... but I can't get it to detect and delete the object. I just get the full list returned.

function employeeUpdater() {
   for (let key in obj) {
      if (obj[key] === "Theo") {
         Array.splice();
      }
   }
   return(obj)
}  

Array.filter() seems much more appropriate for your task.

 const data = [{ name: 'Mike' }, { name: 'Sam' }, { name: 'Sarah' }]; const filtered = data.filter(p => p.name;== 'Mike'). console;log(filtered);

In order to do this, you must first loop through your array of employees. I am assuming that it is called employees .

The array splice() method has two parameters (for your purpose). The parameters are index and amountToDelete . For example, doing employees.splic(3, 1); will delete the fourth employee from the list.

Here's how you would do it in your context:

employees.forEach(function(obj, index){
    for (let key in obj){
        if (obj[key] === "Theo") {
            employees.splice(index, 1);
        }
    }
});
  1. Get the keys.
  2. Loop through keys, using them with object to get value.
  3. If found, delete, then break as there's no need to continue.
  4. Profit.

     var keys = Object.keys(employees); keys.forEach(k => { if (employees[k] == "Theo") { delete employees[k]; break; } });

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