For...in loop inside a function

hi all,

in this exercise, Mosh asked to create a function and check if two objects areEqual, meaning with the same value in each key-value pair. In his solution, he checked each key-value pair individually. Is there a possibility to use a loop to check the key-value pairs?

const myAddress1 = new CreateAddress('e', 'f', 'g');
const myAddress2 = new CreateAddress('e', 'f', 'g');


function CreateAddress(street, city, zipcode) {
  this.street = street;
  this.city = city;
  this.zipCode = zipcode;
}

Below is what I am trying to do instead of doing each comparison separated using the && operator.

function areEqual(obj1, obj2) {
  for (let key of obj1) {
    for (let value of obj2) {
      return (obj1[key] === obj2[value])
    }
  }
}

console.log(areEqual(myAddress1, myAddress2))

But this is not working! Any implementation?

1 Like

Maybe it is because you are using a for…of loop instead a for…in loop for objects?

I am not taking this course, so I do not know what exactly Mosh’s question is asking. But from your address example, I assume that the objects you are comparing have the same properties or keys? If that is the case, then I think you don’t need the second for loop, as the key in obj1 can also be used for obj2. Here is what I will do using a for loop:

function checkEqualObjectsValues(obj1, obj2){
     let result = true;
     for(const key in obj1){
        if(obj1[key] !== obj2[key]){
           result = false;
           break
        }
     }
     return result;
}

console.log(checkEqualObjectsValues(myAddress1, myAddress2))
1 Like

@19jai your solution has limitation for below test case

obj1 = {id:1, name:'azhar'}
obj2 = {id:1, name:'azhar', number:1234}

if we know that obj1 and obj2 created using Map Object then simply

function checkEqualObjectsValues(obj1, obj2){
     for(const [key, value] of obj1){
        if(value !== obj2.get(key))
           return false;
     }
     return obj1.size === obj2.size;
}
1 Like

this peice of code will not work as we know that obj1 is an Map object not array

1 Like