Remove Falsy Values from JavaScript Objects Recursively

🚀 Day 27/30 – Compact Object in JavaScript 🧹 | Remove Falsy Values Recursively Given an object or array obj, return a compact object. ✅ What is a Compact Object? It’s the same structure as the original — but with all keys containing falsy values removed. 🔎 Falsy Values in JavaScript: false 0 "" (empty string) null undefined NaN ⚠️ This removal applies: To the main object To nested objects To nested arrays You may assume: obj is valid JSON (output of JSON.parse) Arrays are treated as objects (indices are keys) 🧠 Example 1 obj = {"a": null, "b": [false, 1]} Output: {"b": [1]} 🧠 Example 2 obj = { "a": 0, "b": { "c": false, "d": 5 } } Output: { "b": { "d": 5 } } 💡 JavaScript Solution (Recursive) var compactObject = function(obj) { if (Array.isArray(obj)) { const result = []; for (let item of obj) { const compacted = compactObject(item); if (Boolean(compacted)) { result.push(compacted); } } return result; } else if (obj !== null && typeof obj === "object") { const result = {}; for (let key in obj) { const compacted = compactObject(obj[key]); if (Boolean(compacted)) { result[key] = compacted; } } return result; } return obj; }; 🔎 Why This Works Recursively traverse structure If array → build new filtered array If object → build new filtered object Only keep values where Boolean(value) === true Preserves structure while removing falsy values Time Complexity: O(n) Space Complexity: O(n) (n = total nested elements) 🧠 What This Teaches ✅ Recursive traversal ✅ Object vs Array handling ✅ Deep data transformation ✅ JSON structure processing ✅ Real-world data cleaning logic ⚡ Real-World Use Cases Cleaning API payloads Removing empty form fields Optimizing database writes Sanitizing user input Preprocessing configuration files #JavaScript #30DaysOfJavaScript #CodingChallenge #Recursion #DataStructures #FrontendDevelopment #WebDevelopment #SoftwareEngineering #CleanCode #LearnToCode #Programming #InterviewPrep #ProblemSolving #JSDeveloper #100DaysOfCode JavaScript remove falsy values Compact object JavaScript Remove null values from object JS Recursive object cleaning JS Deep object traversal JavaScript JSON data cleaning JavaScript JavaScript interview question recursion Remove empty keys from object JS

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories