Iterate over an object and remove false property in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 } }
}
raja
Updated on 12-Oct-2020 11:37:36

Advertisements