Skip to the code
+25 XP

#741 Deep Merge Two Configs

medium

A build tool merges a user's config file over its defaults. Write deepMerge(base, override) that returns a new object and changes neither input:

  • Start from all of base's keys.
  • For each key in override: if its value is null, the key is removed from the result. If both base and override have plain objects (not arrays) at that key, merge them with the same rules. Otherwise the override's value replaces the base's value (arrays are replaced, not combined).

Values in the result must not be shared with the inputs: copy nested objects and arrays.

Example 1

Input: base = {"mode":"production","output":{"dir":"dist","clean":false},"plugins":["a"]}, override = {"output":{"clean":true},"plugins":["b"]}
Output: {"mode":"production","output":{"dir":"dist","clean":true},"plugins":["b"]}

output is merged key by key, while plugins is replaced.

Example 2

Input: base = {"devtool":"source-map","cache":true}, override = {"devtool":null}
Output: {"cache":true}

null removes the key.

Constraints

  • Each input is a JSON object with at most 10^5 values, nested at most 1,000 levels deep.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).