David Dury
David Dury

Reputation: 5717

JavaScript / AngularJS modify property in array

I have the following AngularJS model:

$scope.Model = {
     Users : [{
         UserId: '',
         FirstName: '',
         LastName: ''
     }],
     Products :[{
         ProductId: '',
         Price: ''
     }]
};

If I populate this array with N users, and one user has id=1, how can I update that specific user (with id=1) the property LastName?

So for example if I will get a new AngularJS model:

$scope.UserToUpdate ={
   UserId: 1,
   LastName: "Smith"
};

I want to loop through the $scope.Model array and update the user with id=1 but only the FirstName property.

P.S. I don't know at what position the target user object in the array it is so basically can be at $scope.Model.Users[0] or $scope.Model.Users[1] or $scope.Model.Users[10] or at $scope.Model.Users[N] ...

Upvotes: 0

Views: 55

Answers (4)

mikelt21
mikelt21

Reputation: 2768

You can just loop through your list of users

for (var i = 0; i < $scope.Model.Users.length; i++) {
    if($scope.Model.Users[i].UserId === $scope.UserToUpdate.UserId) {
        $scope.Model.Users[i].LastName = $scope.UserToUpdate.LastName;
        break;
    }
}

EDIT: Actually harish's answer is on to something too. Here's another solution using $filter:

var matchedUsers = $filter('filter')($scope.Model.Users, { UserId: $scope.UserToUpdate.UserId });
if (matchedUsers.length > 0) {
    matchedUsers[0].LastName = $scope.UserToUpdate.LastName;
}

And don't forget to add the $filter service as a parameter in your controller declaration for this second solution.

Upvotes: 3

Asik
Asik

Reputation: 7977

Try this! working demo http://plnkr.co/edit/scyV79HqqA7nOG9h4ezH?p=preview . Please check the console log.

angular.forEach($scope.Model[0].Users, function(value1, key1) {
    var i = 0;
    angular.forEach(value1, function(value, key) {
      if (key == 'UserId' && $scope.UserToUpdate.UserId == value) {
        $scope.Model[0].Users[i].LastName = $scope.UserToUpdate.LastName;
      }
      i++;
    });

  });

The above code updating the Model object LastName property based on UserToUpdate object (id=1)

Upvotes: 0

harishr
harishr

Reputation: 18065

you can use $filter

      var user = $filter('filter')($scope.Model.Users, 'UserId == 1');

you are read more about $filter('filter') here

Upvotes: 0

Amir Popovich
Amir Popovich

Reputation: 29846

$scope.UserToUpdate = 
   $scope.Model.Users.filter(function(user) { return user.FirstName == "test"; })[0];

BTW: you can add a check if the user exists..

Upvotes: 0

Related Questions