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' }

Updated on: 01-Oct-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements