[英]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.我需要使用 function 删除该员工的完整 object(所有键值对),该 function 将遍历数组并检查键值
firstName
并根据名称删除 ZA8CFDE6331BD59EB2AC96F8911C4B66666。
Lets say the name is "Mike".可以说名字是“迈克”。
I want to use the splice command and a for loop.我想使用 splice 命令和 for 循环。 this is what I have currently... but I can't get it to detect and delete the object.
这就是我目前所拥有的......但我无法让它检测和删除 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. Array.filter()
似乎更适合您的任务。
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
.我假设它被称为
employees
。
The array splice()
method has two parameters (for your purpose).数组
splice()
方法有两个参数(用于您的目的)。 The parameters are index
and amountToDelete
.参数是
index
和amountToDelete
。 For example, doing employees.splic(3, 1);
比如做
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);
}
}
});
Profit.利润。
var keys = Object.keys(employees); keys.forEach(k => { if (employees[k] == "Theo") { delete employees[k]; break; } });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.