Checking 'undefined' or 'null' of any Object
You can use _.isNil()
to detect undefined
or null
. Since you're using Array.filter()
, you want to return the results of !_.isNil()
. Since i
is supposed to be an object, you can use !_.isNil(i && i.id)
.
Note: you are using Array.filter()
as Array.forEach()
. The callback of Array.filter()
should return a boolean, and the result of the filter is a new array.
const selectedItem = [
undefined,
{},
{ id: 5 },
undefined,
{ id: 7 },
];
const result = selectedItem.filter(i => !_.isNil(i?.id));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
You can also use _.reject()
and save the need to add !
:
const selectedItem = [
undefined,
{},
{ id: 5 },
undefined,
{ id: 7 },
];
const result = _.reject(selectedItem, i => _.isNil(i?.id));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Use typeof i.id === 'undefined'
to check for undefined
and i.id === null
to check for null
.
You could write your own helper functions to wrap any logic like what LoDash has. The condition with !!i && !!i.id
is only looking for falsy values (empty string, 0
, etc), not only null
or undefined
.