Search code examples
javascriptobjectmergelodash

How do I merge two objects while omitting null values with lodash


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!


Solution

  • Use _.mergeWith:

    let merged = _.mergeWith(
        {}, defaultValues, product,
        (a, b) => b === null ? a : undefined
    )
    

    Updated fiddle