user4043491
user4043491

Reputation:

Angular JS copy Object to another into a for loop

Trying to copy a part of a json object into another json object (thats a filter), into a for loop, under a conditional statement, it doesn't work.

This work but a plain to write an array:

$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
    if (omegaCandidats[i].dateRdv==date){ 
        $scope.candidats.push(
            {
             "id"       :omegaCandidats[i].id,
             "prenom"   :omegaCandidats[i].prenom,
             "nom"      :omegaCandidats[i].nom,
             "heure"    :omegaCandidats[i].heure,
             "dateRdv"  :omegaCandidats[i].date
            }
        )
    };
};

This doesn't work, and that's what i want to do. Its logical and should work:

$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
    if (omegaCandidats[i].dateRdv==date){ 
        $scope.candidats[i] = omegaCandidats[i];
    };
};

This one work but only get one value of the for loop its useless:

$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
    if (omegaCandidats[i].dateRdv==date){ 
        $scope.candidats[0] = omegaCandidats[i];
    };
};

Upvotes: 2

Views: 1476

Answers (3)

Deblaton Jean-Philippe
Deblaton Jean-Philippe

Reputation: 11398

I think this should work :

$scope.candidats=[];
    for (i=0;i<omegaCandidats.length;i++){

        if (omegaCandidats[i].dateRdv==date){ 

            //$scope.candidats.push(omegaCandidats[i]);

            $scope.candidats.push(angular.copy(omegaCandidats[i]));
            //copy will create a new reference for your object.
        };
    };

The code you had is not logical to me :

$scope.candidats=[];
    for (i=0;i<omegaCandidats.length;i++){
        if (omegaCandidats[i].dateRdv==date){ 
            $scope.candidats[i] = omegaCandidats[i]; // This can't work because $scope.candidats[i] is not defined.
            // You would also have an inconsistent array
        };
    };

Upvotes: 0

jcubic
jcubic

Reputation: 66560

You can use filter array method, try this:

$scope.candidats = omegaCandidats.filter(function(item) {
    return item.dateRdv==date;
});

Upvotes: 2

Chris Charles
Chris Charles

Reputation: 4446

what about using a filter:

$scope.candidats = omegaCandidats.filter(function(candidat){ 
    return candidat.dateRdv == date;
});

Upvotes: 3

Related Questions