Comparing Angularjs arrays

Asked

Viewed 582 times

1

I’m creating a device for Cell... only I had the following problem: I need to compare if an account has not been paid, and send a warning...

q accounts must be paid every month.. if you do not find the name in the other array generate the warning

[{"tipo":0,"classe":"Entrada","nome":"111","categoria":"Meu salario","cor":"MediumSeaGreen"}]

list of account for conference if paid...

[{"classe":"Entrada","data":"10-11-2016","dia":"Qua","tipo":0,"categoria":"Meu salario","cor":"MediumSeaGreen","nome":"111","comentario":"","total":5},{"classe":"Saída","data":"10-11-2016","dia":"Qua","tipo":1,"nome":"1","categoria":"Despesa fixa variavel","cor":"DodgerBlue","total":1}]

1 answer

1


You can use the method forEach to pass through each element of the array and inside it do the check.

Example:

var obj1 = [{"tipo":0,"classe":"Entrada","nome":"111","categoria":"Meu salario","cor":"MediumSeaGreen"}]
var obj2 = [{"classe":"Entrada","data":"10-11-2016","dia":"Qua","tipo":0,"categoria":"Meu salario","cor":"MediumSeaGreen","nome":"111","comentario":"","total":5},{"classe":"Saída","data":"10-11-2016","dia":"Qua","tipo":1,"nome":"1","categoria":"Despesa fixa variavel","cor":"DodgerBlue","total":1}]

//Verificação
angular.forEach(obj1, function(item1, key) {
    angular.forEach (obj2, function(item2, key) {
        if(item1.categoria == item2.categoria) {
            item1.pago = true;
        }
    })
})

What happens is, in this part: angular.forEach(obj1, function(item1, key) for each element of array obj1 he is identified through item1, then you can access each property through item1.propriedade. key refers to the $index of the object within that array, if necessary, it is there. The same logic applies to the second array.

Note that I’m doing 2 angular.forEach, because you need to navigate by 2 array, therefore, for each element of the first array, you need to compare with each element of the second array.

The treatment of item1.pago = true was an example, but that’s where you apply the 'Paid' status as best for you.

  • I had other problems it was not only that more run I had to reset the new array in a few moments because that and within a function... ai happens manipulation, then had a few more problems in general and that msm vlw :D

  • Beauty, but the important thing is you understand the logic and apply it in your method. If it worked, wonder! How nice that I helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.