Purging unwanted properties in js object

alwarg

Alwar G

Posted on June 10, 2020

Purging unwanted properties in js object

Hi All,

Now we are going to discuss about Purging unwanted properties in js object

Let's consider we have the following object

let obj = {
  name: 'Alwar G',
  email: '',
  g: [],
  info: {
    personal: {
      family members: ['father', 'mother'],
      age: undefined,
      address: {
       no: '',
       street: '1st avenue',
       place: 'chennai'
      }
    },
    business: {
      partners: [],
      group: {},
      isApproved: null
      address: {
        street: '2nd avenue',
        place: 'Chennai'
      }
    }
   }
 }
Enter fullscreen mode Exit fullscreen mode

From the above object, i want to remove the properties which are having the following values

  • null
  • undefined
  • Empty object({})
  • Empty String('')
  • Empty Array([])

What? That means our output will be as shown in below

{
  name: 'Alwar G',
  info: {
    personal: {
      family members: ['father', 'mother'],
      address: {
       street: '1st avenue',
       place: 'chennai'
      }
    },
    business: {
      address: {
        street: '1st avenue',
        place: 'chennai'
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

how do we do it? Thinking too much of logic.
wait

I got the answer. Let's see the below code

function getPurgedObj(obj){
   let stringfiedObj = JSON.stringify(obj, (key, value) => {
     return ['', null].includes(value) || (typeof value === 'object' &&(value.length === 0 || Object.keys(value).length === 0)) ? undefined : value;
   });
   let resObj = JSON.parse(stringfiedObj);
   let isEmptyPropsPresent = ['{}', '[]', '""', 'null'].some((key) => stringfiedObj.includes(key))
   if(isEmptyPropsPresent) {
     return getPurgedObj(resObj);
   }
   return resObj;
 }
 getPurgedObj(obj);
Enter fullscreen mode Exit fullscreen mode

Here we are using JSON.stringify method to remove the empty properties(unwanted properties).

We are using replacer function from the JSON.stringify method for removing the empty properties.
What? Are you sure?🤷🏻‍♂️

yes. Let me explain

let stringfiedObj = JSON.stringify(obj, (key, value) => {
    return ['', null].includes(value) || (typeof value === 'object' &&(value.length === 0 || Object.keys(value).length === 0)) ? undefined : value;
});
Enter fullscreen mode Exit fullscreen mode

Actually, If you return the undefined value for the particular property in the replacer function, then the property will not be considered for the stringification.

  • For empty string and null values we have the check of ['', null].includes(value)
  • For empty arrays and empty objects we have the check of typeof value === 'object' &&(value.length === 0 || Object.keys(value).length === 0)

    Where

    1. value.length === 0 for Empty Array
    2. Object.keys(value).length === 0 for Empty Object
  • For undefined values, the above two conditions will fail. So the given value will be returned from the replacer function. Here the given value is undefined. So, it will not be taken for stringification

That's ok. But Why we are having the extra code for checking the empty properties?

let resObj = JSON.parse(stringfiedObj);
let isEmptyPropsPresent = ['{}', '[]', '""', 'null'].some((key) => stringfiedObj.includes(key))
 if(isEmptyPropsPresent) {
   return getPurgedObj(resObj);
 }
 return resObj;
Enter fullscreen mode Exit fullscreen mode

Actually JSON.stringify method stringifies the object with only one level of nesting. That's why we are again checking the result object string with empty properties of {}, [], "", 'null' and call the getPurgedObj with the parsed object string argument function agin(recursion) untill we get the clean object.

Now we got the output😍. I hope you learned something. Thank you for reading this post.

Note:
Here, i am removing the properties based on my preference(no empty properties). You can also remove the properties like which are having the value of no string. So it's upto you. You have to choose which properties you want to remove.

💖 💪 🙅 🚩
alwarg
Alwar G

Posted on June 10, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related