'Lodash cloneDeepWith to omit undefined
I wrote a customozer function to omit the undefined values of the object with cloneDeepWith. However on the immutable return, it is not digging in recursively. Here is my code:
import { cloneDeepWith, pickBy, omit } from 'lodash';
const obj = {
a0: true,
b0: true,
c0: undefined,
obj1: {
a1: true,
b1: true,
c1: undefined
}
};
cloneDeepWith(obj, value => {
const objWithUndefinedValue = pickBy(obj, (value) => value === undefined);
const keysWithUndefinedValue = Object.keys(objWithUndefinedValue);
return omit(obj, keysWithUndefinedValue);
});
However it doesn't recurse after the first return. Is it possible to accomplish this with lodash stock functionality?
Solution 1:[1]
This can be solved by using recursively lodash transform method via:
const obj = { a0: true, b0: true, c0: undefined, obj1: { a1: true, b1: true, c1: undefined } };
const cloneMe = (obj) => _.transform(obj, (r, v, k) =>
_.isUndefined(v) ? null : _.isObject(v) ? r[k] = cloneMe(v) : r[k] = v, {})
console.log(cloneMe(obj))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
You could also do this in ES6 only via Object.entries & reduce:
const obj = { a0: true, b0: true, c0: undefined, obj1: { a1: true, b1: true, c1: undefined } };
const cloneMe = (obj) => {
return Object.entries(obj).filter(([k,v]) =>
v != undefined).reduce((r,[k,v]) => {
r[k] = (v instanceof Object) ? cloneMe(v) : v
return r
},{})
}
console.log(cloneMe(obj))
You can additionally extend the check for object if instance of Object is not sufficient etc.
Solution 2:[2]
There's another alternative using DeepDash, which is a standalone, complementary library that offers recursive versions of Lodash functions.
Once DeepDash has been mixed in with Lodash (deepdash(_)), you can write a prune function like this:
const prune = obj => _.filterDeep(obj, (v) => !_.isUndefined(v))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | aalaap |
