乐闻世界logo
搜索文章和话题

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

1个答案

1

When using Lodash to merge two objects, we typically employ the _.merge or _.assign methods for object merging. However, if we aim to omit null values during the merge process, we need to adjust the approach slightly or implement additional logic.

Method 1: Using _.mergeWith to Customize Merge Rules

Lodash provides the _.mergeWith function, which allows us to define custom merge behavior. We can leverage this function to check for null values during merging and exclude them if encountered.

javascript
import _ from 'lodash'; const objectA = { a: 1, b: null, c: 3 }; const objectB = { a: null, b: 2, d: 4 }; const customizer = (objValue, srcValue) => { if (srcValue === null) { return objValue; } } const result = _.mergeWith({}, objectA, objectB, customizer); console.log(result); // Output: { a: 1, b: 2, c: 3, d: 4 }

In this example, the customizer function inspects the source object's value; if it is null, it returns the target object's value, ensuring null values are not overwritten in the final result.

Method 2: Filter Objects Before Merging

An alternative approach involves filtering out all key-value pairs with null values prior to merging. We can achieve this using _.omitBy, then merge the cleaned objects with _.merge or _.assign.

javascript
import _ from 'lodash'; const objectA = { a: 1, b: null, c: 3 }; const objectB = { a: null, b: 2, d: 4 }; const cleanObjectA = _.omitBy(objectA, _.isNull); const cleanObjectB = _.omitBy(objectB, _.isNull); const result = _.merge(cleanObjectA, cleanObjectB); console.log(result); // Output: { a: 1, b: 2, c: 3, d: 4 }

This method first removes all null-valued keys from each object before merging, guaranteeing no null values appear in the final output.

Summary

Based on the specific context, select the appropriate method. If you require flexible handling of merge rules (e.g., managing not only null but also other special values needing custom treatment), _.mergeWith is an excellent choice. For straightforward null value exclusion, the filtering-and-merging approach is often more direct and efficient.

2024年6月29日 12:07 回复

你的答案