Skip to content

Instantly share code, notes, and snippets.

@xkeshav
Created September 29, 2021 16:54
Show Gist options
  • Save xkeshav/f64b7fb468a3b36c628f982cfbe116b7 to your computer and use it in GitHub Desktop.
Save xkeshav/f64b7fb468a3b36c628f982cfbe116b7 to your computer and use it in GitHub Desktop.
interview questioin: how to deep merge 2 objects
const user1 = {name: 'alpha', age: 23, address: {street: 'alpha road', city: 'Pune'}, gender: {sex: 'male'}};
const user2 = {name: 'beta', age: 25, address: {street: 'beta road', state: 'Maharashtra'}};
const deepMerge = (source, target) => {
for(const [key, val] of Object.entries(source)) {
if(val !== null && typeof val === 'object') {
if(target[key] === undefined) {
target[key] = {...val}
}
deepMerge(val, target[key]);
} else {
target[key] = val;
}
}
return target;
};
//alternative approach
const d_merge = (s,t) => {
const res = {...s, ...t};
// console.log({res});
const keys = Object.keys(res);
for(const key of keys) {
const t_prop = t[key];
const s_prop = s[key];
// console.log({t_prop, s_prop});
// if 2 object have conflicts
if(typeof(t_prop) === 'object' && typeof(s_prop) === 'object') {
res[key] = d_merge(s_prop, t_prop);
}
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment