The callback function for $.each method takes two parameters:
$.each(car.wheels, function(i,item) {
if (item.name == "Michelin") {
delete car.wheels[i];
}
});
But this is not the best solution.Usually, delete operator is used to delete properties from an object.If you use it on array, delete will remove the array item, but will not reindex the array or update its length. This makes it appears as if it is undefined:
var car = {
type: "Fiat",
model: "500",
color: "White",
wheels: [{
name: "Goodyear",
color: "Red"
}, {
name: "Goodyear",
color: "Yellow"
}, {
name: "Goodyear",
color: "Black"
}, {
name: "Michelin",
color: "Blue"
}]
};
$.each(car.wheels, function(i,item) {
if (item.name == "Michelin") {
delete car.wheels[i];
}
});
console.log(car);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The solution is to use filter method which accepts a callback provided function applied on every item in the array.
var car = {
type: "Fiat",
model: "500",
color: "White",
wheels: [{
name: "Goodyear",
color: "Red"
}, {
name: "Goodyear",
color: "Yellow"
}, {
name: "Goodyear",
color: "Black"
}, {
name: "Michelin",
color: "Blue"
}]
};
car.wheels=car.wheels.filter(function(wheel){
return wheel.name!='Michelin';
});
console.log(car);
$.each(). It is a messed up function that evolved piecemeal. Use.forEach()or a more appropriate function like.filter()as in Alexandru's code. If you must use$.each()for some reason (no, really, don't!) at least don't usethisat all inside the callback. That makes things really confusing. Instead, use the two named arguments to the callback as doublesharp mentioned.