Loading article...
Flattening an object converts a nested object structure into a single-level object where nested keys are joined with a delimiter (like underscore). This is commonly used for form data serialization, API payloads, and configuration management.
function flattenObject(obj, keyName = '', result = {}) { // Loop through all keys in the object Object.keys(obj).forEach(key => { // Construct new key path, joining with underscore if prefix exists const newKey = keyName ? `${keyName}_${key}` : key; const value = obj[key]; // Debug: Log current key and value console.log(`π‘ Processing key: "${newKey}"`, value); if (typeof value === 'object' && value !== null && !Array.isArray(value)) { // π Recurse into nested object console.log(`π Recursing into nested object at key: "${newKey}"`); flattenObject(value, newKey, result); } else { // β Base case: assign value directly console.log(`β Setting result["${newKey}"] =`, value); result[newKey] = value; } }); // Debug: Show intermediate result at current level console.log('π¦ Current flattened result:', result); return result; }
const input = { a: 1, b: { c: 2, d: { e: 3 } }, f: null, g: [4, 5] }; const flat = flattenObject(input); console.log('β Final Flattened Object:', flat);
π‘ Processing key: "a" 1 β Setting result["a"] = 1 π‘ Processing key: "b" { c: 2, d: { e: 3 } } π Recursing into nested object at key: "b" π‘ Processing key: "b_c" 2 β Setting result["b_c"] = 2 π‘ Processing key: "b_d" { e: 3 } π Recursing into nested object at key: "b_d" π‘ Processing key: "b_d_e" 3 β Setting result["b_d_e"] = 3 π‘ Processing key: "f" null β Setting result["f"] = null π‘ Processing key: "g" [4, 5] β Setting result["g"] = [4, 5] π¦ Current flattened result: { a: 1, b_c: 2, b_d_e: 3, f: null, g: [4, 5] }
value !== null.result as an accumulator.Test your understanding with 3 quick questions