Take any variable from an array that has a certain id in Angularjs

Asked

Viewed 356 times

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;

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

Ex: $scope.listademercadoria[id = 2].quantidade = 0; If it worked, it would take only arrays containing id=2 and select the quantity for 0.

Is there any way to do this without using the $filter? If not, how would you end up with the $filter?

2 answers

2


Unfiltered:

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;
  • At which point it arrow the property 'quantity', parallel to 'id', to 0?

  • 1

    @Guilhermesilvadeoliveira in the example nowhere, now just you take the variable fitlrado and manipulate as you please.

1

Using Javascript only (ES5):

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

Source.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.