Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Merge two objects in JavaScript ignoring undefined values
When merging two objects in JavaScript, you may want to ignore undefined values to avoid overwriting valid data. The spread operator alone doesn't handle this logic, so we need a custom approach.
The Problem
Consider these two objects where some properties have undefined values:
const A = { activity: 'purchased', count: undefined, time: '09:05:33' };
const B = { activity: 'purchased', count: '51', time: undefined };
// Simple spread operator overwrites values
const simpleSpread = { ...A, ...B };
console.log("Simple spread:", simpleSpread);
Simple spread: { activity: 'purchased', count: '51', time: undefined }
Notice that time becomes undefined because B's undefined value overwrites A's valid value.
Solution: Custom Merge Function
We need a function that prioritizes truthy values over falsy ones:
const A = { activity: 'purchased', count: undefined, time: '09:05:33' };
const B = { activity: 'purchased', count: '51', time: undefined };
const mergeObject = (A, B) => {
let res = {};
Object.keys({...A, ...B}).map(key => {
res[key] = B[key] || A[key];
});
return res;
};
console.log(mergeObject(A, B));
{ activity: 'purchased', count: '51', time: '09:05:33' }
How It Works
The function uses the logical OR operator (||) to select the first truthy value:
-
Object.keys({...A, ...B})gets all unique keys from both objects -
B[key] || A[key]picks B's value if truthy, otherwise A's value - Both
undefinedandnullare falsy, so valid values take priority
Alternative: Using Object.assign with Filter
const mergeIgnoringUndefined = (obj1, obj2) => {
const filtered1 = Object.fromEntries(
Object.entries(obj1).filter(([key, value]) => value !== undefined)
);
const filtered2 = Object.fromEntries(
Object.entries(obj2).filter(([key, value]) => value !== undefined)
);
return { ...filtered1, ...filtered2 };
};
const A = { activity: 'purchased', count: undefined, time: '09:05:33' };
const B = { activity: 'purchased', count: '51', time: undefined };
console.log(mergeIgnoringUndefined(A, B));
{ activity: 'purchased', count: '51', time: '09:05:33' }
Comparison
| Method | Handles undefined | Handles null | Performance |
|---|---|---|---|
| Spread operator | No | No | Fast |
| Custom merge with || | Yes | Yes | Medium |
| Filter + spread | Yes | No (keeps null) | Slower |
Conclusion
Use custom merge functions when you need to prioritize truthy values over falsy ones. The || operator approach is simple and handles both undefined and null values effectively.
Advertisements
