gallien
gallien

Reputation: 131

For Each loop in JavaScript are making me mad

My problem is pretty simple. I'm trying to update a list of objects (localDatz) with another list of objects received after an AJAX request (data). So It consists in two loops.. But when I try to update two objects, only one object is updated. There is something I really don't understand. Any help ?

    // fetch the localdata first
            var localData = getAll();

// Loop through my 'localData'
$.each(localData.features, function(index,feature){

        // Loop through the new data that are received
        $.each(data.features, function(){
            newFeature = this;

            if (feature.properties.id==newFeature.properties.id){

            // i think here is the problem..but can't figure out how to fix it
            // I remove the old feature and push the new one
            localData.features.splice(index,1);                                                                   
            localData.features.push(newFeature);


            }

    });

});

Upvotes: 0

Views: 723

Answers (1)

freakish
freakish

Reputation: 56587

You are modyfing the list which you loop over with this code:

if (feature.properties.id==newFeature.properties.id){
    localData.features.splice(index,1);
    localData.features.push(newFeature);
}

and not only modyfing the list entries, but the order as well (you push to the end of the list), which messes up .forEach loop. Use simply:

if (feature.properties.id==newFeature.properties.id){
    localData.features[ index ] = newFeature;
}

There is no need for using .splice at all.

Upvotes: 1

Related Questions