Search code examples
javascriptangulartypescriptangular7

Typescript: Iterate Through Each Member between Two Classes and Flag Difference in Angular


How do I compare two class models and find corresponding differences? Following are two models which have exact same members, and we need to compare.

Is there an algorithm in Typescript which conducts this? * A new result class should be created with class members and boolean different flag?

Looking for a easy way in Typescript algorithm. It needs to accept any class,

Note: Some members in class contain a class itself.

currently

enter image description here

Class:

export class PropertyLocation {   
    streetName: string;
    streetType: string;
    postdirectional?: string;
    unitNumber?: string;
    unitType?: string;
    city: string;
    state?: string;
    postalCode: number;
    postalCodeExtension?: string;

    effectiveStartDate: Date;
    addressChangeReason?: AddressChangeReasonDto
    addressSource?: SourceOfAddressDto;
}

Result Class array sample:

if there is more optimal storage method, feel free to modify

export class DifferenceClass {   
    ClassMember: string;
    DifferentFlag: boolean
}

looking for code solution, refraining from third party libraries as company does not prefer


Solution

  • Why not just build a method/function into your class that runs the comparison. You could do this by comparing each property individually (typing everything out) or just looping every key in your class and comparing it to every key in the passed in object.

    class DifferenceClass {   
        constructor(classMember, differenceFlag) {
          this.ClassMember = classMember;
          this.DifferenceFlag = differenceFlag;
        }
    }
    class Person {
      constructor(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
      }
      isSame(person) {
        if (person instanceof Person) {
          const differences = [];
          for (const key in person) {
            if (this[key] !== person[key]) {
              differences.push(new DifferenceClass(key, true));
            }
          }
          return differences;
        } else {
          throw new Error('Object is not a Person class');
        }
      }
    }
    
    const p1 = new Person('John', 'Doe');
    const p2 = new Person('Jane', 'Doe');
    console.log('Should be empty', p1.isSame(p1));
    console.log('Should have diff results', p1.isSame(p2));
    console.log('should be an exception', p1.isSame(1));