簡體   English   中英

返回具有特定屬性的數組中的對象

[英]Return object in array with specific property

我寫新自己的JS函數時相當新,我正在努力解決這個問題。

我想運行一個對象數組,找到一個匹配特定ID的對象,然后返回該對象。

到目前為止,這就是我所擁有的:

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

$scope.teamDetails是我的數組, $scope.whichTeam變量包含我正在檢查的正確ID。

最終,我希望能夠將函數產生的對象分配給$scope.thisTeam變量,因此我可以在視圖中調用其屬性。

任何幫助,將不勝感激。

謝謝。

您可以使用Array#some ,如果找到則結束迭代

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

移動你的$scope.thisTeam = team; if檢查中。

var findTeam = function() {
  $scope.teamDetails.forEach(team) {
     if(team.team_id === $scope.whichTeam) {
         $scope.thisTeam = team;
     }
  }
};
$scope.team = $scope.teamDetails.filter(function (team) {
  return team.team_id === $scope.whichTeam;
})[0];

您需要使用數組的過濾方法。 它創建了與給定謂詞匹配的新數組元素(返回布爾值的函數)。 然后你只需要取第一個值。

您也可以使用find ,但尚未在每個瀏覽器中實現。

它看起來像這樣:

$scope.team = $scope.teamDetails.find(function (team) {
  return team.team_id === $scope.whichTeam;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM