1

I'm fairly new with writing my own JS functions, and I'm struggling with this one.

I want to run through an array of objects, find an object that matches a particular ID, and then return that object.

So far this is what I have:

var findTeam = function() {
  $scope.extraTeamData.forEach(team) {
     if(team.team_id === $scope.whichTeam) { return team }
  }
    $scope.thisTeam = team;
};

$scope.teamDetails is my array, and the $scope.whichTeam variable holds the correct ID which I am checking against.

Ultimately I want to be able to assign the object that results from the function to the $scope.thisTeam variable, so I can call its properties in the view.

Any help would be appreciated.

Thanks.

Paulos3000
  • 3,355
  • 10
  • 35
  • 68
  • is there only one result? – Nina Scholz May 19 '16 at 18:00
  • Can you tell us what issue(s) you're experiencing with your current implementation? – smaili May 19 '16 at 18:02
  • Instead of `return team`, you could just do `$scope.thisTeam = team;` – Matt Burland May 19 '16 at 18:02
  • Thanks Matt Burland - that trims it down a bit. I want to write it in the most efficient way possible, and to ultimately result in one variable which holds the desired object. – Paulos3000 May 19 '16 at 18:04
  • forEach requires a callback. your `forEach(team) {` is syntacticaly wrong. it should be `forEach(function (team) {` or if ES6 then `forEach(team => {`. and there is a missing closing parenteses. – Nina Scholz May 19 '16 at 18:09

3 Answers3

2

You could use Array#some which ends the iteration if found

var findTeam = function() {
    $scope.extraTeamData.some(function (team) {
        if (team.team_id === $scope.whichTeam) { 
            $scope.thisTeam = team;
            return true;
        }
    });
};
Paulos3000
  • 3,355
  • 10
  • 35
  • 68
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Move your $scope.thisTeam = team; to within the if check.

var findTeam = function() {
  $scope.teamDetails.forEach(team) {
     if(team.team_id === $scope.whichTeam) {
         $scope.thisTeam = team;
     }
  }
};
smaili
  • 1,245
  • 9
  • 18
0
$scope.team = $scope.teamDetails.filter(function (team) {
  return team.team_id === $scope.whichTeam;
})[0];

You need to use filter method of array. It creates new array elements that match given predicate (function that return boolean value). Then you simply take first value.

You can also use find, but it is not implemented in every browser yet.

It would look something like this:

$scope.team = $scope.teamDetails.find(function (team) {
  return team.team_id === $scope.whichTeam;
});
sielakos
  • 2,406
  • 11
  • 13