Cho 2 đối tượng A và B. Gộp chúng sao cho key có giá trị truthy không bị ghi đè bởi falsy.
Ví dụ: A={activity:'purchased', count:undefined, time:'09:05:33'}, B={activity:'purchased', count:'51', time:undefined} → {activity:'purchased', count:'51', time:'09:05:33'}.
Mã thực hiện
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));
Kết quả
{ activity: 'purchased', count: '51', time: '09:05:33' }