0

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.

AppDreamer
  • 1,266
  • 3
  • 16
  • 34
  • 1
    It's actually *encouraged* to [answer your own question](https://stackoverflow.com/help/self-answer). But that involves posting your question as a question and then posting an answer to it. Right now you just have an answer in the place a question should be, which *is* bad form. Could you [edit] the question to be a question and then post an answer to it? – jcalz Apr 22 '22 at 23:55
  • Thanks. I was in a hurry, but took your advice to break them apart. The main thing is to save someone else from going through what I just went through. Cheers! – AppDreamer Apr 23 '22 at 00:41

1 Answers1

1

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;
        }
    }
}
AppDreamer
  • 1,266
  • 3
  • 16
  • 34