I know the _.defaults function works to put default values for an object with keys that are undefined. However it doesn't work with keys that are null. Is there way to achieve this?
Thanks to @Jacque for the explanation about null values. However due to unfortunate inherited code, the object I'm working on returns null values even though it's intended for undefined. Here's my approach in achieving this in a more declarative way by omitting the null properties which will result into undefined, as a result will create defaults 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>
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