I've researched how to merge two JavaScript objects while omitting null values, so far I've tried using merge, assign, clone without success.
Here is my test (JSFiddle) :
let defaultValues = {code: '', price: 0, description: ''}
let product = {code: 'MyCode', price: null, description: 'Product Description'}
//Merge two objects
let merged = _.merge({}, defaultValues, product)
console.log(merged)
//My result
{code: 'MyCode', price: null, description: 'Product Description'}
//My expected result
{code: 'MyCode', price: 0, description: 'Product Description'}
I use VueJS framework, when I have these null properties on some inputs (with v-model), I receive an exception.
Thanks!
Lodash helps in working with arrays, strings, objects, numbers, etc. The _. merge() method is used to merge two or more objects starting with the left-most to the right-most to create a parent mapping object. When two keys are the same, the generated object will have value for the rightmost key.
To remove a null from an object with lodash, you can use the omitBy() function. If you want to remove both null and undefined , you can use . isNull or non-strict equality.
To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.
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.
Use _.mergeWith
:
let merged = _.mergeWith(
{}, defaultValues, product,
(a, b) => b === null ? a : undefined
)
Updated fiddle
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