Get any variable of an array that has a certain id in AngularJS

2

With the following code, I am saying that in the second array contained in the object $scope.listademercadoria there is the property "quantity", and I am declaring it as value 0.

$scope.listademercadoria[1].quantidade = 0;

Is there a way to select only the array that contains a certain id as property?

Ex: $scope.listademercadoria[id = 2].quantidade = 0; If it works, it would only take the arrays that contain id = 2 and would set the amount to 0.

Is there any way I can do this without using $filter ? If not, how would it look like $filter ?

    
asked by anonymous 12.10.2017 / 06:43

2 answers

2

No filter:

var filtrado = $scope.listademercadoria(function(item) {
  return item.id === 2;
})[0];

With $filter :

var filtrado = $filter('filter')($scope.listademercadoria, {id: 2})[0];

Then you use the attribute you want:

filtrado.quantidade = 0;
    
12.10.2017 / 06:48
1

Using only JavaScript (ES5):

$scope.listademercadoria.filter(function(i){ return i.id == 2; });

Source.

    
12.10.2017 / 15:57