DEV Community

Alwar G
Alwar G

Posted on

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.

Top comments (2)

Collapse
 
bharathpanchak profile image
Bharath Panchakarla

Hi Alwar G,
Your code will go into an infinite loop if familyMembers: ['father', 'mother', null]. I think you did not consider this case.. Thanks though for the initial boost for my requirement.

Happy coding!

Collapse
 
alwarg profile image
Alwar G • Edited

@bharathpanchak Thank you for poiniting out my mistake.
I tried one solution

function getPurgedObj(obj){
      let stringfiedObj = JSON.stringify(obj, (key, value) => {
        if (Array.isArray(value)) {
          value = value.filter((val) => !['', null].includes(val));
        }
        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;
    }
Enter fullscreen mode Exit fullscreen mode

Please share if you have better solution