Flatten a nested object into dot-separated prefixed keys
You are tasked with creating a function, flattenWithPrefix, that flattens a nested object. The challenge lies in ensuring that as the object is flattened, the keys in the resulting object are prefixed with their parent keys, joined by periods (‘.’). This means that for every level of nesting within the original object, its key is concatenated with its parent key(s), creating a clear hierarchical representation of the original nested structure in the flattened object. To flatten nested objects with prefixes, Object.entries() makes it easy to walk each key.
This problem presents a common scenario in data manipulation, where nested structures need to be simplified for easier processing or storage, while still retaining a trace of their original hierarchical organization. Such a function can be particularly useful when dealing with configurations, translations, or any data that is naturally hierarchical but needs to be flattened for practical reasons.
Example Usage:
Input: { a: { b: { c: 1 }, d: 2 } }
Output: { "a.b.c": 1, "a.d": 2 }
Input: { x: { y: 10, z: { w: 20 } } }
Output: { "x.y": 10, "x.z.w": 20 }
In these examples, notice how each key in the output object is a string that represents the path to the corresponding value in the input object. The function essentially transforms the nested object into a ‘flat’ object where each key-value pair is accessible at the top level, with keys indicating the original nested structure.
Your implementation of flattenWithPrefix should work for objects of arbitrary depth and complexity, handling all the quirks of object iteration in JavaScript, such as inherited properties. The focus is not just on achieving the task but on writing clean, efficient, and maintainable code that could be integrated into larger codebases.