Languages

JavaScript - remove undefined and null values from object using lodash

0 points
Asked by:
Mikolaj
519

I have an object like:

var object = { a: null, b: undefined, c: 3 }

How can I remove all the null and undefined properties?

1 answer
0 points
Answered by:
Mikolaj
519

1. Remove all falsy value

If you want to remove all the falsy values, you can use _.pickBy() method combined with _.identity().

Syntax:

_.pickBy(objectName, _.identity);

Practical example:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
</head>
<body>
  <script>
    
    var myObject = { a: 1, b: null, c: undefined, d: '', e: false };

    var result = _.pickBy(myObject, _.identity);

    console.log(JSON.stringify(result, null, 4));

  </script>
</body>
</html>

2. Remove only null and undefined values

If you want to remove only null and undefined values, you can omit them using omitBy() method.

Syntax:

_(objectName).omitBy(_.isUndefined).omitBy(_.isNull).value();

Practical example:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
</head>
<body>
  <script>
    
    var myObject = { a: 1, b: null, c: undefined, d: '', e: false };

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

    console.log(JSON.stringify(result, null, 4));

  </script>
</body>
</html>

 

References

  1. _.pickBy – Lodash Docs v4.17.11
  2. _.identity – Lodash Docs v4.17.11
  3. _.omitBy – Lodash Docs v4.17.11
  4. _.isNull – Lodash Docs v4.17.11
  5. _.isUndefined – Lodash Docs v4.17.11
  6. _.prototype.value() – Lodash Docs v4.17.11
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join