Skip to content

Instantly share code, notes, and snippets.

@SujitSingh
Last active July 26, 2019 11:27
Show Gist options
  • Save SujitSingh/3c49ffa92114ebce862090f6e930682d to your computer and use it in GitHub Desktop.
Save SujitSingh/3c49ffa92114ebce862090f6e930682d to your computer and use it in GitHub Desktop.
Compare n-level Objects/Arrays to get differences between them

Compare n-level Objects/Arrays to get differences between them

function compareObjs(base, val2, keyName) {
  if (base && val2) {
    if (base.constructor === Object && val2.constructor === Object) {
      let baseArr = Object.keys(base);
      let ar2 = Object.keys(val2);
      let baseLen = baseArr.length;
      let ar2Len = ar2.length;
      if (baseLen && ar2Len) { // if both objects have some values
        let tmpObj = Object.assign({}, base, val2); // create an Object with all keys
        let tmpArr = Object.keys(tmpObj);
        for (let key of tmpArr) {
          const targetKey = keyName ? `${keyName} > ${key}` : key;
          compareObjs(base[key], val2[key], targetKey);
        }
      } else {
        logMismatch();
      }
    } else if (base.constructor === Array && val2.constructor === Array) {
      let baseLen = base.length;
      let ar2Len = val2.length;
      if (baseLen === ar2Len) { // if both array have same length
        for (let i = 0; i < baseLen; i++) {
          const targetKey = keyName ? `${keyName}[${i}]` : `[${i}]`;
          compareObjs(base[i], val2[i], targetKey);
        }
      } else {
        logMismatch();
      }
    } else if (base !== val2) {
      logMismatch();
    }
  } else if (base !== val2) {
    logMismatch();
  }

  function logMismatch() {
    console.log(`Mismatch '${keyName}' - `, base, ' vs ', val2);
  }
}

// Test
var obj1 = {name: 'Sujit', title: 'Singh', names: ['Sujit', 'Bhola'], names1: ['Sujit', 'Bholu'],  othr1: ['Sujit', 'Bhola'], roll: 22}; 
var obj2 = {name: 'Sujit', title: 'Other', names: ['Sujit', 'Bhola'], names1: ['Sujit', 'Bhola'],  othr2: ['Sujit', 'Bhola']};
compareObjs(obj1, obj2);

// Test
var obj1 = {name: 'Sujit', names: ['Sujit', 'Bhola'], inner: { name: 'MyName', others: ['other name'] }, additional: {}}; 
var obj2 = {name: 'Sujit', names: 'Sujit, Bhola', inner: { name: 'MyName', others: [] }};
compareObjs(obj1, obj2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment