Exercise 8: Deep Merge Objects

Problem Statement

Function `deepMerge(target, source)` banao jo dono objects ko deeply merge kare. Example: deepMerge({a: 1, b: {c: 2}}, {b: {d: 3}}) => {a: 1, b: {c: 2, d: 3}}

Sample Output:

deepMerge({a: 1, b: {c: 2}}, {b: {d: 3}}) => {a: 1, b: {c: 2, d: 3}}
deepMerge({x: 1}, {x: 2}) => {x: 2}

Solution

const deepMerge = (target, source) => {
  const result = {...target};
  for (const key in source) {
    if (source.hasOwnProperty(key)) {
      if (typeof source[key] === "object" && source[key] !== null && !Array.isArray(source[key]) &&
          typeof result[key] === "object" && result[key] !== null && !Array.isArray(result[key])) {
        result[key] = deepMerge(result[key], source[key]);
      } else result[key] = source[key];
    }
  }
  return result;
};

Explanation

Overall Goal:

  • Objects ko deeply merge karna.

Real world:

  • Configuration: merge configs.
  • State management: deep state updates.