EN
JavaScript - remove undefined and null values from object using lodash
1 answers
0 points
I have an object like:
xxxxxxxxxx
1
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:
xxxxxxxxxx
1
_.pickBy(objectName, _.identity);
Practical example:
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
5
</head>
6
<body>
7
<script>
8
9
var myObject = { a: 1, b: null, c: undefined, d: '', e: false };
10
11
var result = _.pickBy(myObject, _.identity);
12
13
console.log(JSON.stringify(result, null, 4));
14
15
</script>
16
</body>
17
</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:
xxxxxxxxxx
1
_(objectName).omitBy(_.isUndefined).omitBy(_.isNull).value();
Practical example:
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
5
</head>
6
<body>
7
<script>
8
9
var myObject = { a: 1, b: null, c: undefined, d: '', e: false };
10
11
var result = _(myObject).omitBy(_.isUndefined).omitBy(_.isNull).value();
12
13
console.log(JSON.stringify(result, null, 4));
14
15
</script>
16
</body>
17
</html>
References
0 commentsShow commentsAdd comment