
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Merge two objects in JavaScript ignoring undefined values
Suppose, we have two objects, say A and B like these −
const A = { activity: 'purchased', count: undefined, time: '09:05:33' }; const B = { activity: 'purchased', count: '51', time: undefined };
We are required to write a JavaScript function that merges these two objects, keeping in mind if any key has a truthy value then it should not be overwritten by a key having falsy value.
If we do this simply by using the spread operator, it will not keep track of truth or falsy values.
Therefore, we have to do this using an iterative approach.
Example
Following is the code −
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));
Output
This will produce the following output on console −
{ activity: 'purchased', count: '51', time: '09:05:33' }
- Related Articles
- How to merge two JavaScript objects?
- Merge two arrays with alternating Values in JavaScript
- How to merge properties of two JavaScript Objects dynamically?
- How to merge two arrays with objects in one in JavaScript?
- How can I merge properties of two JavaScript objects dynamically?
- How to merge two different array of objects using JavaScript?
- JavaScript program to merge two objects into a single object and adds the values for same keys
- Merge objects in array with similar key JavaScript
- JavaScript reduce sum array with undefined values
- How can we merge two JSON objects in Java?
- Fetch values by ignoring a specific one in JavaScript?
- Undefined in JavaScript
- How to merge two arrays in JavaScript?
- How to merge two strings alternatively in JavaScript
- JavaScript undefined Property

Advertisements