0

I am writing a comparison function to check if two objects are identical, including nested arrays.

Note: There is another similar question using angular.equals() but there is no equivalent in Angular 2+. I am using Angular 8.

The purpose is to check if a value has been changed in a form in Angular 8 reactive forms. The selected answer to this similar question provides an answer on how to compare two objects, however the check function is single-level only. I need to be able to check if two arrays of objects are the same (order does not matter).

Here is a JS Fiddle: https://jsfiddle.net/xtrn4quf/

// Check if two objects are the same
// TODO: Update to iterate over nested arrays, order of array elements should not matter
function checkSame(a, b) {

  let isSame = true;

  for (let prop in a) {
    if (a[prop] !== b[prop]) {
      // ISSUE: Returning not the same if value is an array
      console.log(`${prop} not the same! ${JSON.stringify(prop)}`);
      isSame = false;
    }
  }

  return isSame;
}

let a = {
  'Title': 'Example title',
  'Description': 'Example description',
  'Items': [{
    'NestedObject1': true
  }, {
    'NestedObject2': true
  }, {
    'NestedObject3': true
  }]
};

let b = {
  'Title': 'Example title',
  'Description': 'Example description',
  'Items': [{
    'NestedObject1': true
  }, {
    'NestedObject2': true
  }, {
    'NestedObject3': true
  }]
};

let c = {
  'Title': 'Example title',
  'Description': 'Example description',
  'Items': [{
    'NestedObject1': true
  }, {
    'NestedObject2': false
  }, {
    'NestedObject3': true
  }]
};

console.log(checkSame(a, b)); // returns false but should return true, 'Items' array of objects is not the same but it should be the same
console.log(checkSame(a, c)); // returns false but should return true
pengz
  • 2,279
  • 3
  • 48
  • 91

0 Answers0