harmonius cool
harmonius cool

Reputation: 347

Replace object in json with angular.forEach

I'm trying to replace an object with another object, using the angular.forEach function:

angular.forEach(agenda,function(evt){

    if(evt.identifiant  == event.identifiant){

        evt = event;
    }

});

For some reason the object evt doesn't get replaced by the event object inside my agenda array. Both evt and event are correct JSON objects (calendars events).

I wonder if my syntax is correct, or if I should do this another way?

EDIT:

This code is working, but it is not what I want, as it is changing only a value inside my evt object:

angular.forEach(agenda,function(evt){

    if(evt.identifiant  == event.identifiant){

        evt.start = event.start;
    }
});

Upvotes: 1

Views: 569

Answers (2)

Hasta Tamang
Hasta Tamang

Reputation: 2263

angular.forEach(agenda,function(evt, index){

    if(evt.identifiant  == event.identifiant){

        agenda[index] = event;
    }

});

Upvotes: 0

Dacre Denny
Dacre Denny

Reputation: 30370

If I understand your question correctly, then you'll want to update the angenda object itself by assigning the filtered event to the current key that corresponds to evt like so:

/* The iteration handler on forEach provides access to the key of the current value */
angular.forEach(agenda,function(evt, key){

    if(evt.identifiant == event.identifiant){

        /* Assign/update the value for current key of agenda like so */
        agenda[key] = event;
    }
});

For more information on angular.forEach see the documentation - hope that helps!

Upvotes: 1

Related Questions