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'
}
}
}
}
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'
}
}
}
}
how do we do it? Thinking too much of logic.
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);
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;
});
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
- value.length === 0 for
Empty Array
- Object.keys(value).length === 0 for
Empty Object
- value.length === 0 for
For undefined values, the above two conditions will fail. So the given
value
will be returned from the replacer function. Here the given value isundefined
. 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;
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)
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!
@bharathpanchak Thank you for poiniting out my mistake.
I tried one solution
Please share if you have better solution