9951 explained code solutions for 126 technologies


javascript-lodashHow can I use Lodash to remove undefined values from an object in JavaScript?


Lodash provides a utility function _.omitBy to remove undefined values from an object. The following example code will demonstrate how to use it:

const _ = require('lodash');

const obj = {
  a: 'hello',
  b: undefined,
  c: 'world'
};

const modified = _.omitBy(obj, _.isUndefined);
console.log(modified);

Output example

{ a: 'hello', c: 'world' }

The code does the following:

  1. requires the lodash library.
  2. Creates an object obj with two defined and one undefined property.
  3. Uses _.omitBy to remove all properties with an undefined value.
  4. console.logs the modified object.

Helpful links

Edit this code on GitHub