Clean your JSON object before saving into Cloud Firestore database

If you have a registration form and you are collecting user's inputs to json object like
user = {
  'first_name' : 'Amir',
  'middle_name':'',
  'last_name':'Ismail'
  'age' : 25,
  'address' : '',
  'phone':null
};
notice middle_name, address, and phone fields have no value (empty string and null). If you want to save this in Cloud Firestore database, these fields will be saved which is not recommended because you are losing one of the advantages of  NoSQL document database which any document should contain only fields have value(except your business case requires that field to be exist in all documents even has no value).

To remove empty fields you have to check each input value and save only fields that have value. But if you have big form with many input fields or you have many forms checking each fields will be a nightmare and your code will be dirty.
So I tried to write a TypeScript function that takes any json object and build new object contains only fields have values.
export class AppUtils {

  static cleanObject(input: any): any {
      let output: any = {};
      //loop over object fields 
      for (var key in input) {
        //check if field have value or not
        if (input.hasOwnProperty(key) && input[key] != null && input[key] !== '') {
          //check if primitive type or object
          if (typeof (input[key]) === 'object') {          
            var subOutput = AppUtils.cleanObject(input[key]);
            
            if (Object.keys(subOutput).length !== 0) {
              output[key] = subOutput;
            }
          }
          else {
            output[key] = input[key];
          }
        }
      }
      return output;
  }
}
If we passed our user object to this function
let cleanObj = AppUtils.cleanObject(user);
the new object will be
cleanObj = {
  'first_name' : 'Amir',
  'last_name':'Ismail'
  'age' : 25
};

Comments

Popular posts from this blog

ASP.Net MVC : ActionLink with bootstrap icon

ASP.Net MVC : Conditional Validation using ValidationAttribute

Android : How to change progress bar color at runtime programmatically?