我的代码填充数组中缺少逻辑会创建重复项 - javascript

时间:2015-08-05 03:49:59

标签: javascript angularjs

我正在试图弄清楚如何不在我的数组中复制对象。请注意,在注释器数据模型中,索引0和1是重复的,因为insertproperty函数我进行了id比较,这对于具有唯一ID的列表是理想的,但我仍然必须在这种情况下应用它以确保im关联到正确用户。

评论数据模型:

var comments = [{id:1, comment_text:"foo", user_id:1},
{id:2, comment_text:"bar", user_id:1},
{id:3, comment_text:"brew", user_id:2}];

合并后的评论者数据模型:

var commentors = [{id:1, name:"ed", comment_text:"foo"},
{id:1, name:"ed", comment_text:"foo"},
{id:2, name:"sue", comment_text:"brew"}];

期望的结果:

var commentors = [{id:1, name:"ed", comment_text:"foo"},
{id:1, name:"ed", comment_text:"bar"},
{id:2, name:"sue", comment_text:"brew"}];
$scope.insertProperty=function(){           
        for(var i=0;i<$scope.commentors.length;i++){
            for(var j=0;j<$scope.comments.length;j++){
                if($scope.commentors[i].id==$scope.comments[j].user_id)                               
                $scope.commentors[i].comment_text=$scope.comments[j].comment_text;                   
            }
        }
    }

$scope.commentors = [];
  var getUser = function(id) {
        UserService.GetUserById(id, $localStorage.CurrentUser.auth_token)
        .success(function (data) {
          var data = angular.fromJson(data);   
          $scope.commentors.push(data);
          $scope.insertProperty();
        }).error(function(error, status) {
            //do something         
        });
    };

$scope.GetComments = function(){
PostService.GetComments($stateParams.id, $localStorage.auth_token)
          .success(function (data) {      
            var data = angular.fromJson(data);                 
            angular.forEach(data, function(user){
                getUser(user.user_id);})                       
          }).error(function(error, status) {
            //do something        
          });
    }

1 个答案:

答案 0 :(得分:0)

$scope.result=[];
$scope.insertProperty = function(){
for(var i=0; i<$scope.comments.length; i++)
{
  for(var j=0; j<$scope.commentors.length; j++)
 {
  if($scope.commentors[i].id==$scope.comments[j].user_id) 
  {
     $scope.result.push($scope.commentors[i].id, $scope.commentors[i].name, $scope.commentors[j].common_text);
  }
 }
}

$scope.commentors = $scope.result;