Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove undefined and null values from an object using lodash?

People also ask

How do you remove undefined and null values from an object?

To remove all null and undefined values from an object:Use the Object. keys() method to get an array of the object's keys. Use the forEach() method to iterate over the array and delete all null or undefined values using the delete operator.

How do you remove an undefined and null from an array?

To remove all undefined values from an array:Use the Array. filter() method to iterate over the array. Check if each value is not equal to undefined and return the result. The filter() method will return a new array that doesn't contain any undefined values.

Is null or undefined Lodash?

Lodash helps in working with arrays, strings, objects, numbers, etc. The _. isNil() method is used to check if the value is null or undefined. If the value is nullish then returns true otherwise it returns false.


You can simply chain _.omit() with _.isUndefined and _.isNull compositions, and get the result with lazy evaluation.

Demo

var result = _(my_object).omit(_.isUndefined).omit(_.isNull).value();

Update March 14, 2016:

As mentioned by dylants in the comment section, you should use the _.omitBy() function since it uses a predicate instead of a property. You should use this for lodash version 4.0.0 and above.

DEMO

var result = _(my_object).omitBy(_.isUndefined).omitBy(_.isNull).value();

Update June 1, 2016:

As commented by Max Truxa, lodash already provided an alternative _.isNil, which checks for both null and undefined:

var result = _.omitBy(my_object, _.isNil);

If you want to remove all falsey values then the most compact way is:

For Lodash 4.x and later:

_.pickBy({ a: null, b: 1, c: undefined }, _.identity);
>> Object {b: 1}

For legacy Lodash 3.x:

_.pick(obj, _.identity);

_.pick({ a: null, b: 1, c: undefined }, _.identity);
>> Object {b: 1}

The correct answer is:

_.omitBy({ a: null, b: 1, c: undefined, d: false }, _.isNil)

That results in:

{b: 1, d: false}

The alternative given here by other people:

_.pickBy({ a: null, b: 1, c: undefined, d: false }, _.identity);

Will remove also false values which is not desired here.


if you are using lodash, you can use _.compact(array) to remove all falsely values from an array.

_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]

https://lodash.com/docs/4.17.4#compact


Just:

_.omit(my_object, _.isUndefined)

The above doesn't take in account null values, as they are missing from the original example and mentioned only in the subject, but I leave it as it is elegant and might have its uses.

Here is the complete example, less concise, but more complete.

var obj = { a: undefined, b: 2, c: 4, d: undefined, e: null, f: false, g: '', h: 0 };
console.log(_.omit(obj, function(v) { return _.isUndefined(v) || _.isNull(v); }));