- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterate over an object and remove false property in JavaScript
Suppose, we have a JSON object like this −
const obj = { a: { someKey: { propOne: '', enabled: true } }, b: { someKey: { propOne: '', enabled: false } }, c: { someKey: { propOne: '', enabled: false } }, someKey: { ab: { propOne: '', enabled: true } } };
We are required to write a JavaScript function that takes in one such object and removes all the "enabled" properties recursively from the object in place that have a falsy value.
Example
The code for this will be −
const obj = { a: { someKey: { propOne: '', enabled: true } }, b: { someKey: { propOne: '', enabled: false } }, c: { someKey: { propOne: '', enabled: false } }, someKey: { ab: { propOne: '', enabled: true } } }; const deleteFalsyKey = obj => { const keys = Object.keys(obj); keys.forEach(key => { if(obj[key].enabled === false){ delete obj[key]; return; }; if(obj[key] && typeof obj[key] === 'object'){ deleteFalsyKey(obj[key]); if (!Object.keys(obj[key]).length) { delete obj[key]; }; } }); }; deleteFalsyKey(obj); console.log(obj);
Output
The output in the console −
{ a: { someKey: { propOne: '', enabled: true } }, someKey: { ab: { propOne: '', enabled: true } } }
- Related Articles
- How to iterate over objects in array and sum a property in JavaScript
- Java Program to Iterate over an ArrayList
- How to remove a property from a JavaScript object?
- How do we remove a property from a JavaScript object? - JavaScript
- What is an object in JavaScript and access any property ?**
- Remove number properties from an object JavaScript
- How do I remove a property from a JavaScript object?
- Iterate through Object keys and manipulate the key values in JavaScript
- How to remove an object using filter() in JavaScript?
- How to iterate over arrays and objects in jQuery?
- Iterate over a dictionary in Python
- Iterate over a list in Python
- Iterate over a set in Python
- What are the different ways to iterate over an array in Java?
- How to modify key values in an object with JavaScript and remove the underscore?

Advertisements