Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic way to convert all instances of null to undefined in Typescript

I am wanting to write a function that converts all instances of a property of any object that is null to undefined. Many of my objects have nested objects as properties or arrays of values/objects.

My first thought when approaching the problem is to use generics to attempt to catch the type of each of the properties with a generic type and then to convert the value of that property from null to undefined as needed.

I am hoping to write a function that is generic enough to work across any of the different types and sized objects I have across my code code base.

I haven't been able to find an easy way to have an unknown number of generic types, so my next thought is that I'll have to use the any type everywhere. Is there a way around this?

I'd also love some advice on the approach/algorithm itself as well. My thought is that I'll probably need to recursively check each property to see if it itself is an object with sub properties, and I'll also need to iterate any arrays found that might have a null value as well, or have an object that will need to be recursively checked as well.

The problems/questions I need to solve/answer:

  1. Should I use Generics or Any?
  2. If i use generics is there a way to dynamically assign new generic types as a new type is found?
  3. Does typescript have an easier way to recursively parse objects?

My current approach is something like:

inputObjectKeys.map(key, index) =>

then have a function that converts null to undefined, ignores non object types, and recurses if its an object.

I'm assuming I'd want to use a Breadth First Search or Depth First Search (I'm leaning towards Breadth First Search for this particular task). I'm assuming since i need to visit every node i might be better off with DFS simply because of the memory usage.

like image 782
Grant Williams Avatar asked May 16 '18 15:05

Grant Williams


1 Answers

A bit late to the party, but I think Grant's answer can be simplified a bit. How about this one:

function removeNulls(obj: any): any {
    if (obj === null) {
        return undefined;
    }
    if (typeof obj === 'object') {
        for (let key in obj) {
            obj[key] = removeNulls(obj[key]);
        }
    }
    return obj;
}
like image 186
Marten S Avatar answered Oct 06 '22 01:10

Marten S