How to concatenate two objects by omitting null values โโusing lodash
I've researched how to merge two JavaScript objects by omitting null values, so far I've tried to use merge, assign, clone with no 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 am using VueJS framework, when I have these null properties on some inputs (with a v-shaped model) I get an exception.
Thank!
+3
source to share
1 answer
Use _.mergeWith
:
let merged = _.mergeWith(
{}, defaultValues, product,
(a, b) => b === null ? a : undefined
)
+6
source to share