This is a question similar to How to remove undefined and null values from an object using lodash?. However, the solutions proposed there do not conserve the constructor. In addition to that, I want to only delete those keys which starts, say with '_'.
Here is what I am looking for, and can't seem to manage to get from lodash :
Input : new Cons({key1 : 'value1', key2 : {key21 : 'value21', _key22: undefined}, key3: undefined, _key4 : undefined})
Output :
{key1 : 'value1', key2 : {key21 : 'value21'}, key3: undefined}
where for example function Cons(obj){_.extend(this, obj)}
I have a solution with omitBy
using lodash, however, I loose the constructor information (i.e. I cannot use instanceof Cons
anymore to discriminate the object constructor). forIn
looked like a good candidate for the recursive traversal but it only provides me with the value
and the key
. I also need the path in order to delete the object (with unset
).
Please note that:
- the object is any valid javascript object
- the constructor is any javascript valid constructor, and the object comes with the constructor already set.
- the resulting object must have
instanceof whatevertheconstructorwas
still true
Is there a better solution (with lodash or else)?