score:-2

const A = { activity: 'purchased', count: undefined, time: '09:05:33' }
const B = { activity: 'purchased', count: '51', time: undefined }
const AKeys = Object.keys(A);
const BKeys = Object.keys(B);
const C = {};
AKeys.forEach(element=>A[element] && C[element]=A[element])
BKeys.forEach(element=>B[element] && C[element]=B[element])

score:-2

let A = { activity: 'purchased', count: undefined, time: '09:05:33' }
let B = { activity: 'purchased', count: '51', time: undefined }

for (let a in A) {
  if (A[a] === undefined) 
    delete A[a];
}

for (let b in B) {
  if (B[b] === undefined) 
    delete B[b];
}

let c = {...A, ...B} // this will merge identical key/values

console.log(c)

score:0

You could merge the objects by having a look to the entries of the second object and take only key/value pairs without undefined as value.

const
    merge = (a, b) => Object.assign(
        {},
        a,
        ...Object.entries(b).map(([k, v]) => v === undefined ? {} : { [k]: v })
    ),
    a = { activity: 'purchased', count: undefined, time: '09:05:33' },
    b = { activity: 'purchased', count: '51', time: undefined };

console.log(merge(a, b));

score:1

You could use lodash's merge command. C = _.merge(A,B);

score:2

let A = { activity: 'purchased', count: undefined, time: '09:05:33' }
let B = { activity: 'purchased', count: '51', time: undefined }

let C={}
Object.keys({...A,...B}).map(key=>{
C[key]=B[key]||A[key]
})
console.log(C)

score:3

The spread operator(...) works well to merge objects, and there is a simple solution to remove undefined using JSON.stringify() and JSON.parse(). See below example:

const A = { activity: 'purchased', count: undefined, time: '09:05:33' };
const B = { activity: 'purchased', count: '51', time: undefined };

//If you don't care about date objects then only use below method 
const C = {...JSON.parse(JSON.stringify(A)), ...JSON.parse(JSON.stringify(B))};

console.log(C);


Related Query

More Query from same tag