无法在角度中创建新的对象数组(循环内部循环)

时间:2015-10-07 14:09:29

标签: javascript ajax angularjs

我要做的是比较两个阵列" similarBands"和#34; artistsArray"。我想记下两个数组中发生的每个匹配(这是我创建计数器背后的逻辑)。我正在寻找的最终结果是一个新的对象数组(称为newMatchingArray)这两个数组的所有匹配,它将采用name属性和matches属性(表示有多少匹配)。

该功能现在可以正确找到匹配但不会增加"计数器"在每场比赛中,它都停在2.我对JS和AJAX都很陌生,很抱歉显而易见的问题/缺乏技术细节。谢谢!

  $scope.getBandsLikeThisBand = function(){
          $.ajax({
            async: false,
            type: 'Get',
            url: 'https://api.spotify.com/v1/artists/' + $scope.bandId + '/related-artists',
            success: function(data){
              console.log($scope.allTheArtists);
              $scope.similarBandsArray = data.artists;
              $scope.similarMathesArray = [];
              $scope.newMatchingArray = [];
                for(var i = 0; i < $scope.similarBandsArray.length; i ++){ //going through every related artist from the search
                  var counter = 0;
                  for (var x = 0; x < $scope.allTheArtists.length; x ++){ //going through every artist in the allTheArtistsArray
                    if($scope.similarBandsArray[i].name === $scope.allTheArtists[x].name){
                      counter ++;
                      if (counter > 0){
                        var toBeAddedToMutual = {
                          name: $scope.similarBandsArray[i],
                          count: counter
                        };
                      $scope.newMatchingArray.push(toBeAddedToMutual);
                      }
                    }
                    if($scope.soManyObjects && $scope.soManyObjects.amount > 0 ){
                        $scope.bigBoyArray.push($scope.soManyObjects.name + "and their count is" + ($scope.soManyObjects.amount + 1));
                      }
                  }
                }
                for(var j = 0; j < $scope.similarBandsArray.length; j ++){
                  $scope.allTheArtists.push($scope.similarBandsArray[j]);
                }
              }
            });
          };

2 个答案:

答案 0 :(得分:0)

当您找到第一个匹配项时,counter变为1.您创建一个对象toBeAddedToMutual并将其插入到数组中。如何将计数作为任何其他值?

您的意思是将第二个if-block移出第一个if-block吗?

var counter = 0;
for (var x = 0; x < $scope.allTheArtists.length; x ++){
  if ($scope.similarBandsArray[i].name === $scope.allTheArtists[x].name){
    counter ++;
  }
  if (counter > 0) {
    var toBeAddedToMutual = {
      name: $scope.similarBandsArray[i],
      count: counter
    };
    $scope.newMatchingArray.push(toBeAddedToMutual);
  }
....

正如@FernandoPinheiro建议的那样,您可以使用lambda表达式缩短代码。

angular.forEach($scope.similarBandsArray, function(band) {
  var matches = $scope.allTheArtists.filter(function(artist) {
    return band.name === artist.name;
  });
  if (matches.length) {
    $scope.newMatchingArray.push({
      name: band, // maybe you mean band.name
      count: matches.length
    });
  }
  ....
});

答案 1 :(得分:-1)

查看此库:https://lodash.com/

它具有您的算法可能需要的所有功能,例如数组,过滤器等之间的差异。