Problem 24

Replace keys in object Recursion Challenge

Given an object, an old key name, and a new key name, rename every occurrence of the old key to the new key throughout the entire object, including inside nested objects. The object should be mutated in place.

Function Signature

replaceKeysInObj(obj, oldKey, newKey)

Parameters

  • obj — an object that may contain nested objects.
  • oldKey — a string representing the key to replace.
  • newKey — a string representing the replacement key.

Output

Return the same object with all matching keys renamed. The total number of keys should remain unchanged.

Constraints

  • The function must use recursion.
  • The input object should be mutated in place (not cloned).
  • The function should accept exactly three arguments.

Examples

// Given: obj = {e: {x: 'y'}, t: {r: {e: 'r'}, p: {y: 'r'}}, y: 'e'}
replaceKeysInObj(obj, 'e', 'f')
// obj is now: {f: {x: 'y'}, t: {r: {f: 'r'}, p: {y: 'r'}}, y: 'e'}