Parsing JSON and deleting objects from it is giving error

I have a phonegap application and I want to prune the pictures before downloading. I am passing a JSON object to my function which is

[{"name":"aaa.jpg","link":"https://www.abc.com/aaa.jpg"},"name":"bbb.jpg","link":"https://www.abc.com//bbb.jpg"}]

And using the following function to parse and delete

function prunePictures(pictures) {
    for ( var i = 0; i < entries.length; ++i) {
            var name = entries[i].name;
            $.each(pictures, function(i, obj) {
                if (obj.name == name) {
                    delete pictures[i];
                }
            });
     }
}

But its not going through the loop and I am getting an error “Cannot read property ‘name’ of undefined”

Answer

…you don’t want to delete the picture object. You want to splice it out of the array.

Deleting it leaves a hole in the array, whereas splicing it removes the hole.

var l = entries.length, i = 0, pictureName;

for (; i < l; i += 1) {
    pictureName = entries[i].name;
    pictures.forEach(function (picture, i, arr) {
        if (pictureName === picture.name) { arr.splice(i, 1); }
    });
}

Removes the object in pictures if an object in entities has the same name property.

Leave a Reply

Your email address will not be published. Required fields are marked *