2

I have two objects and I want to compare them from each other, like I need to check and value parallelly, but for this I need to execute only one for loop but I'm not able to make it.
Below is my code:

function traverseObject(object1, object2) {
  var key1;
  var key2;
  for (key1 in object1) {

    for (key2 in object2) {
      console.log('Key1 is -' + key1);
      //console.log('Key2 is -'+key2);
      if (object1.hasOwnProperty(key1) || object2.hasOwnProperty(key2)) {
        console.log('Value1 ' + object1[key1]);
        console.log('Value2 ' + object2[key2]);
        if ((object1[key1] !== null && typeof object1[key1] === 'object') || (object2[key2] !== null && typeof object2[key2] === 'object')) {
          process(object1[key1], object2[key2]);
        }
      }
    }
  }
}

Bu using this it's running first time for outer loop then it read all inner loop values then it read the second value of the outer loop and then again it read all values of the inner loop.
What i want is, this run at same time so that i can compare their values.

4
  • Can you elaborate on how you want to compare their values, do you want to check if object 1 has certain values of object 2? Commented Dec 20, 2019 at 7:43
  • yes i want to compare object on has same value and key as same in object2. Commented Dec 20, 2019 at 7:45
  • if you want to check if both objects are exactly same with same number of properties, you can do that with JSON.stringify(obj1) == JSON.stringify(obj2) Commented Dec 20, 2019 at 7:52
  • No, i need to dynamic traverse the object than compare each key and value. Commented Dec 20, 2019 at 8:10

1 Answer 1

5

You could iterate over all keys that are in both objects:

  for(const key of [...new Set(Object.keys(object1).concat(Object.keys(object2))]) {
    if(key in object2) process(object1[key], object2[key]);
  }
Sign up to request clarification or add additional context in comments.

6 Comments

You can use for...in statement, you don't need to get the array of keys.
@ryeballar no, the behaviour would be different from the code the OP has shown, meaning that inherited properties would be iterated.
You're right, I forgot that OP is using object#hasOwnProperty to solve such issue.
If that's the case, then I think should also check if key is not an inherited property of object2.
@JonasWilms thank you for reply, your solution is only working when key is present in object1 but not in object2, but if a key is not present in object1 but present in object2, then this solution is not working, do you have any other way?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.