简体   繁体   中英

How iterate in one loop for compare the two objects in javascript

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM