Search code examples
prototypejs

How do I delete an element returned from the each enumerator?


I have an array containing objects. Each object has an id field. I want to implement a function that deletes an object by specifying the id. I use .each from prototypejs on the array to step through the objects and check the id. If it matches, how do I actually delete it? I've tried setting the object returned from .each to null, but using FireBug I see that the object is still the same in the array.

EDIT: the objects in the array may in turn contain arrays with objects that may need to be deleted. My function is fine for finding the object to be removed, and I use splice to remove it (using a counter). It seems to me that .each (and the other enumerators like .reject) returns a copy of the object. If I set the object to null then upon inspection the object is still in the array. How would I return a reference of the object that when set to null would actually operate on the object in the array, and not a copy?

Here is the function, the deleteChild function works on the same principal:

function removeControl(controlName) {
var counter = 0;

cont.each(function (existingControl) {
    if (existingControl.id == controlName) {
        existingControl.destroy();
        cont.splice(counter, 1);
    }
    else {  // not found, check control's children
        existingControl.deleteChild(controlName);
    }
    counter++;
}, this);

}


Solution

  • Only use .each when you want to do something to every object. Semantically speaking, you should be using Enumerable.reject in this situation. Think how much easier it will be to understand when you have to fix it in years' time.

    function deleteById(objects, id) {
        return objects.reject(function(obj) {
            return obj.id == id;
        }).each(function(obj) {
            obj.deleteChild(id);
        });
    }