Problem 22

Count key in object Recursion Challenge

Given a nested object and a target key name, return the number of times that key appears anywhere in the object, including inside nested objects.

Function Signature

countKeysInObj(obj, key)

Parameters

  • obj — an object that may contain nested objects.
  • key — a string representing the key to search for.

Output

Return a number representing how many times the key appears in the object tree.

Constraints

  • The function must use recursion.
  • The function should accept exactly two arguments.

Examples

// Given: obj = {e: {x: 'y'}, t: {r: {e: 'r'}, p: {y: 'r'}}, y: 'e'}
countKeysInObj(obj, 'e') → 2
countKeysInObj(obj, 'x') → 1
countKeysInObj(obj, 'y') → 2
countKeysInObj(obj, 't') → 1