Paulos3000 Paulos3000 - 6 months ago 14
AngularJS Question

Getting elements from array based on property values (AngularJS)

I have an array of players, each player is an object that has a number of properties, one is "goals".

var players = [
{
"id":"4634",
"name":"A. Turan",
"number":"0",
"age":"28",
"position":"M",
"goals":"1"
},
{
"id":"155410",
"name":"H. Çalhano?lu",
"number":"0",
"age":"21",
"position":"A",
"goals":"0"
},
{
"id":"4788",
"name":"B. Y?lmaz",
"number":"0",
"age":"30",
"position":"A",
"goals":"2",
}
]


I've written a function to cycle through the array and push every element that has more than '0' goals to an array,
topScorers
. Like so:

$scope.topScorerSearch = function() {
var topScorers = [];
$scope.teamDetails.squad.forEach(function(o) {
if (o.goals > 0) {
topScorers.push(o)
}
});
return topScorers;
}


With the function called as
{{topScorerSearch()}}
.

This returns only players who have scored. Perfect.

However, I want to run this on other properties, which will result in a lot of repetitious code. How can I make this a general purpose function that can be executed on different properties?

I tried including the 'prop' parameter, but it didn't work:

$scope.topScorerSearch = function(prop) {
var topScorers = [];
$scope.teamDetails.squad.forEach(function(o) {
if (o.prop > 0) {
topScorers.push(o)
}
});
return topScorers;
}


...and called the function like this:

{{topScorerSearch(goals)}}


Why doesn't this work? Where am I going wrong?

Answer

I believe the issue is that prop will not resolve to goals because goals is being treated as a variable with a null or undefined value, making prop null or undefined.

If you use the alternative way of accessing object properties object["property"] and use the function {{topScorers("goals")}} it should work out.

Comments