I just started using lodash and have this array of objects, where one of the properties either has an integer or is null. I know how to filter the array for items that are null, but how do I check if it's not null?
Let's say I have something like this:
var users = [
{ 'user': 'barney', 'default': 1 },
{ 'user': 'dino', 'default': 0 },
{ 'user': 'wilma', 'default': 1 },
{ 'user': 'fred', 'default': null }
];
And then I want something like:
var notNullDefault = _.filter(sourceData, ['is_default', ! null ]); // objects with names barney, dino, wilma
var nullDefault = _.filter(sourceData, ['is_default', null ]); // object with name fred
Again, I'm new to lodash, so maybe there's a better way to accomplish this too.
Thanks in advance.
Lodash helps in working with arrays, strings, objects, numbers, etc. The _. isNull() method is used to find whether the value of the object is null. If the value is null then returns true otherwise it returns false.
The _. isNil() method is used to check if the value is null or undefined. If the value is nullish then returns true otherwise it returns false.
Lodash helps in working with arrays, collection, strings, objects, numbers etc. The _. filter() method iterates over elements of collection, returning an array of all elements predicate returns true.
The filter () function has a couple convenient shorthands for dealing with arrays of objects. If you pass a string predicate instead of a function, Lodash will filter by whether that property is truthy or falsy. If your predicate is an object obj, Lodash will filter objects that match the given predicate .
If the predicate returns a falsy value (like null, undefined, 0, or '' ), Lodash filters that value out. The filter () function has a couple convenient shorthands for dealing with arrays of objects. If you pass a string predicate instead of a function, Lodash will filter by whether that property is truthy or falsy.
The Lodash _.isEmpty() Method Checks if the value is an empty object, collection, map, or set. Objects are considered empty if they have no own enumerable string keyed properties. Collections are considered empty if they have a 0 length. Similarly, maps and sets are considered empty if they have a 0 size. Syntax: _.isEmpty( value )
If you pass a string predicate instead of a function, Lodash will filter by whether that property is truthy or falsy. If your predicate is an object obj, Lodash will filter objects that match the given predicate .
This can be solved with _.reject
and _.filter
:
var notNullDefault = _.reject(sourceData, ['default', null]);
var nullDefault = _.filter(sourceData, ['default', null]);
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With