Is there a way to specify default values ββfor null in Lodash or Underscore?
Thanks to @Jacque for explaining the meanings null
. However, due to bad legacy code, the object I am working on returns values null
even though it is intended for undefined
. Here's my approach to achieving this in a more declarative way, omitting the properties null
that will undefined
result in will create default values ββfor its values.
const alphabet = {
a: 'A is for apple',
// b: undefined,
c: 'C is for cake',
d: null,
}
const nonNulls = _.omitBy(alphabet, _.isNull) // Omitting null values.
const longer = _.defaults(nonNulls, {
b: 'B is for boy',
})
console.info('Longer Way', longer)
// Or even shorter
const shorter = _.defaults(_.omitBy(alphabet, _.isNull), {
b: 'B is for boy',
})
console.info('Shorter Way', shorter)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
source to share
The reason for this behavior for the _.defaults
helper is that it undefined
means the property has not been set, but null
is passing the value of an explicitly set value to refer to nothing.
If you still think that your variables should contain null
and be set using a function, then you can use a _.defaultTo
function that returns its first argument normally, and the second, if the first was NaN
, null
or undefined
. You will need all this to loop through all the object keys.
_.forOwn(myObject, function (value, key) {
myObject[key] = _.defaultTo(value, defaultValues[key]);
});
However, this will not set values ββfor variables that are not even defined in the original element as we iterate over its own properties. Plus it's not very effective. If that's what you wanted, you could instead loop over the defaults:
_.forOwn(defaultValues, function (value, key) {
if (myObject[key] === undefined || myObject[key] === null)
myObject[key] = value;
});
function getSampleObject() {
return {
a: null,
b: NaN,
// c: undefined,
d: undefined,
e: 'original'
}};
var defaultValues = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5
};
var myObject = getSampleObject();
_.forOwn(myObject, function (value, key) {
myObject[key] = _.defaultTo(value, defaultValues[key]);
});
console.log('defaultTo', myObject);
var myObject = getSampleObject();
_.defaults(myObject, defaultValues);
console.log('defaults', myObject);
var myObject = getSampleObject();
_.forOwn(defaultValues, function (value, key) {
if (myObject[key] === undefined || myObject[key] === null)
myObject[key] = value;
});
console.log('handmade', myObject);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
source to share