Angular - Search for equal values in two objects

Asked

Viewed 331 times

-2

Good morning, everyone,

I have two objects. In one of them I have only id. In the other several fields, the id of this first object and the name. I need to somehow scan object 2 to find the same id that’s on the first object to know its name, because I only have the id.

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

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

Example of how it looks 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 for your cooperation

3 answers

0

I arrived in the following scenario:

I can see on the console all the records

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

var obj1 = $rootScope.objecto1;

       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;
            } }
        }

Thank you can close the topic, solved by moving to the grid Dice

0

One way to solve this is to loop 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");
}

0

Now they’re clearing things up, thank you very much.

Stayed like this:

var obj1 = $rootScope.objecto1;

       var obj2 = objeto2;


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

I put an Alert inside the if and two records appeared. However, how do I now make the name appear in the correct position of the array?

On the console is appearing like this, as attachedinserir a descrição da imagem aqui

Obs: the $rootScope.obj1 is the obj1 example. However, if you want you can simply do: var obj1 = $rootScope.obj1;. What’s simpler for you.

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

for (i=0; i < 10; i++)
for (var key in obj1) // duas formas de ver o índice usando for
  • If you’re manipulating one array of objects, only use indexOf to find the position where to display the name. https://www.w3schools.com/jsref/jsref_indexof_array.asp

  • 1

    I realized that I can only actually compare objects if I do the fixed position: if (obj1[1]. id === obj2[1]. id)

Browser other questions tagged

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