Reputation: 2164
I'm using the below to loop through an array and add a property to each item of the array.
$scope.addresses = $scope.addresses.map(function(address) {
address.location = "X";
return address;
});
this at the end will return all the items. How can I add a condition to the loop? so I can check a property and the based on that property return only certain addresses where that property is true
?
Any help appreciated!
Upvotes: 0
Views: 1958
Reputation: 300
use filter
$scope.addresses = $scope.addresses.filter(function(address){
return address.location === x;
})
Upvotes: 0
Reputation: 3084
You should use the filter
function
You can read about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Basically filter
is a function the gets a boolean function as a parameter (let's call it f
), and returns an array with all the items that the f
returns true for.
For example:
var mapped = $scope.addresses = $scope.addresses.map(function(address) {
address.location = "X";
return address;
});
var filtered = mapped.filter(function (address) {
return address.location.length > 5;
});
filtered
will hold a collection of the addresses that have a location with more than 5 characters.
Upvotes: 1