IR Punch IR Punch - 4 months ago 16
AngularJS Question

Update document in a JSON Collection using AngularJS

I would like to update document in a JSON Collection using AngularJS

My JSON Collection:

$Scope.employee = {
"staff" :
[
{
"id" : 1,
"Name" : "John",
"email" : "john@abc.com"
},
{
"id" : 2,
"Name" : "Watson",
"email" : "watson@abc.com"
},
{
"id" : 3,
"Name" : "jack",
"email" : "jack@abc.com"
},
{
"id" : 4,
"Name" : "Jim",
"email" : "jim@abc.com"
},
{
"id" : 5,
"Name" : "Rose",
"email" : "rose@abc.com"
}
]
};


Now I need to update the document where
Id = 2
to

$Scope.updateEmployee = {
"id" : 2,
"Name": "Emma",
"email": "emma@abc.com"
};


Kindly assist me how to replace a particular document and I would like to update the
email
of
id = 5
to
hr@abc.com

Answer

You can do this,

$scope.update = function(){
 $scope.employee.staff.forEach(function (item) {
    if (item.id == 2 ) {
        item.Name = "Emma";
        item.email ="emma@abc.com";
    };        
});     
}

DEMO