EN
JavaScript - remove undefined and null values from object using lodash
1
answers
0
points
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
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
0 comments
Add comment