Angular - Searches for equal values on two objects

-2

Good morning,

I have two objects. In one of them I have only the id. In the other several fields, the id of this first object is the name. I need to somehow sweep the object 2 find the same id that is in the first object to know the name of it, since I only have the id.

//objeto 1
$rootScope.obj1 = result.data.value;

//objeto 2
obj2 = result.data.value;

Example of how it is in the browser console:

//obj1
Object {id: 2, createdAt: "2017-12-22T14:01:35.225", updatedAt: "2017-12-22T14:01:35.225", name: "abc", initialDate: "2017-12-22"…}

//obj2
Object {......id: 2}

Thanks in advance for your collaboration

    
asked by anonymous 28.12.2017 / 15:14

3 answers

0

One way to solve this is to loop through one of the objects and compare the attributes:

var obj1 = { 
   id: 2,
   name: 'teste' 
};

var obj2 = { 
   id: 2 
};

for (var key in obj1) {
    if (obj1.id === obj2.id) alert("YAY");
}
    
28.12.2017 / 15:50
0

Now things are getting brighter, thank you very much.

It looks like this:

var obj1 = $ rootScope.object1;

       var obj2 = objeto2;


        for (var key in obj1) {
            if (obj1.id === obj2.id){
               $scope.Nome = obj1.nome;
            }
        }

I placed an alert inside the if and two records appeared. But how do I now to make the name appear in the correct position of the array?

The console is showing up like this, as shown in

Note: $rootScope.obj1 is the obj1 of the example. However, if you want, you can simply do: var obj1 = $rootScope.obj1; . Whatever is simpler for you.

This key is the index of the loop, usually the i of the traditional for . If you want to access a specific item in the list, just use obj1 [key], for example.

for (i=0; i < 10; i++)
for (var key in obj1) // duas formas de ver o índice usando for
    
28.12.2017 / 16:35
0

I came up with the following scenario:

I can see all records in the console

and the variable name is being filled. However I need to return the name in the positions that the id was the same.

var obj1 = $ rootScope.object1;

       var obj2 = objeto2;

        for (var i = 0; i < obj1.length; i++) {
         for(var j = 0; j < obj2.length; j++){
            if (obj1[i].id === obj2[j].id){
               console.log(obj1[i].id);
               console.log(obj2[j].id);
               $scope.Nome = obj1[i].name;
            } }
        }

Thanks you can close the topic, solved by moving to the grid index

    
28.12.2017 / 18:07