How to Remove a null from an Object with Lodash
source link: https://masteringjs.io/tutorials/lodash/remove-null-from-object
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to Remove a null from an Object with Lodash
To remove a null
from an object with lodash, you can use the omitBy()
function.
const _ = require('lodash');
const obj = {a: null, b: 'Hello', c: 3, d: undefined};
const result = _.omitBy(obj, v => v === null); // {b: 'Hello', c: 3, d: undefined}
If you want to remove both null
and undefined
, you can use .isNull
or non-strict equality.
const _ = require('lodash');
const obj = {a: null, b: 'Hello', c: 3, d: undefined};
const result = _.omitBy(obj, _.isNull); // {b: 'Hello', c: 3}
const other = _.omitBy(obj, v => v == null); // {b: 'Hello', c: 3}
Using Vanilla JavaScript
You can use vanilla JavaScript to remove null
s from objects using Object.entries()
and Array filter()
.
However, the syntax is a bit messy.
Lodash omitBy()
is cleaner.
const obj = {a: null, b: 'Hello', c: 3, d: undefined, e: null};
Object.fromEntries(Object.entries(obj).filter(([key, value]) => value !== null)); // { b: "Hello", c: 3, d: undefined }
More Lodash Tutorials
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK