As asked
A third-party API returns deeply nested JSON with inconsistent structure. Write a function that flattens it into a single-level object with dot-notation keys, and handle arrays by appending the index.
Sample answer outline
The function recursively traverses the object; for each value that is a plain object it recurses with the current key as prefix, for arrays it iterates with index as part of the key suffix, for primitives it assigns to the flat output. Edge cases: null values, empty arrays, keys that already contain dots (need escaping or explicit handling). Time complexity O(n) where n is the total number of leaf values.
Reference implementation (javascript)
// Starter: flatten({ a: { b: { c: 1 } }, d: [2, 3] })
// Expected: { 'a.b.c': 1, 'd.0': 2, 'd.1': 3 }
function flatten(obj, prefix = '', result = {}) {
// your implementation here
return result;
}
Expect these follow-ups
- How would you un-flatten this back to the original structure?
- What if two different paths produce the same flattened key?