Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 269
Damosse31 Avatar asked May 17 '17 20:05

Damosse31


People also ask

How do I merge two objects in Lodash?

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.

How do you remove undefined and null values from an object using Lodash?

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.

How do you combine two values of objects?

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.

Is null in Lodash?

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.


1 Answers

Use _.mergeWith:

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

Updated fiddle

like image 120
Ry- Avatar answered Sep 22 '22 06:09

Ry-