javascriptadvanced15 minutes

Build an Optimized Memoized Deep Nested Object Flattener

Create a highly efficient JavaScript function that flattens deeply nested objects into a single-level object with dot-separated keys. Implement memoization to cache and reuse results for previously processed inputs to optimize performance for repeated calls with identical objects.

Challenge prompt

Write a function `flattenObject(obj)` that takes an arbitrarily deep nested JavaScript object and returns a new object with all nested keys flattened into a single level, where nested keys are joined by dots ('.'). For example: `flattenObject({a: {b: 2}})` should return `{ 'a.b': 2 }`. Implement memoization in the function so that if it is called multiple times with the exact same input object reference, it instantly returns the cached flattened result without recomputation. Your solution should handle objects containing nested arrays as values by treating array indices as keys in the flattening process (e.g., `{a: [1, 2]}` becomes `{ 'a.0': 1, 'a.1': 2 }`).

Guidance

  • Recursively traverse the object to access all nested properties and build dot-separated keys.
  • Use a WeakMap to memoize results keyed by the input object reference to avoid memory leaks.
  • Handle arrays by using their indices as keys when flattening.

Hints

  • To memoize based on object references, a WeakMap is ideal since it prevents retaining objects unnecessarily.
  • Check the data type of each value to determine whether to recurse (for objects and arrays) or set the key-value pair.
  • Remember that non-object values (including null) should not be traversed and are terminal values in the flattening.

Starter code

function flattenObject(obj) {
  // Your implementation here
}

Expected output

flattenObject({ a: { b: 1, c: [2, 3] }, d: 4 }) // { 'a.b': 1, 'a.c.0': 2, 'a.c.1': 3, d: 4 }

Core concepts

recursionmemoizationobject traversalJavaScript WeakMap

Challenge a Friend

Send this duel to someone else and see if they can solve it.