AppDreamer
AppDreamer

Reputation: 1426

How to compare two different objects in Typescript

I know it's bad form to answer my own question. Hope to save you hours. There were others that ask this Typescript question and the moderators closed them pointing to rather large threads (4+ pages) of javascript answers that didn't help me and security protocols won't allow me to use libraries.

Here's the question. Working in Angular Typescript, how can I compare two objects of the same class/interface, and allow to ignore certain attributes if I'd like, skipping some attributes by name.

One issue that we face is that "nameof" does not work natively in Typescript, but as we traverse the object, we need to ignore some of the keys by name, and there's no guarantee that the keys will be the same over time. We can't hard code the comparisons. I have an answer that I'll post, but I'm interested in thoughts.

Upvotes: 0

Views: 881

Answers (1)

AppDreamer
AppDreamer

Reputation: 1426

In the example below, field27 and field30 need to be skipped... also, I wanted only the new objs that don't already exist. We want to be able to add easy logic that can then apply later in the function (like using alreadyExists == false). This worked! Hope it helps you!

//create a typescript version of javascript's nameof...
const nameof = <T>(name: Extract<keyof T, string>): string => name;

//use it with 'key in' to iterate through 2 like objects, Obj1 is old and Obj2 was just entered...
for (const key in Obj1) {
    //allow Obj2 to have some gaps, and skip field27 and field30
    if(Obj2[key]!=undefined && (nameof(key) != 'field27' && nameof(key) != 'field30')){
        if(Obj1[key] != Obj2[key]) {
            alreadyExists = false;
            break;
        }
    }
}

Upvotes: 1

Related Questions