Search code examples
node.jsexpressbody-parserexpress-validator

How to change blank fields to null in express js


I want to get all request body params as null if param is blank. Is there any way in the express js.

{
  username: " ",
  password: ""
}

// Get it as

{
  username: null,
  password: null
}

Solution

  • Maybe you want to use this function below:

    let objects = {
        username: ' ',
        password: '',
        testing: [
          {
            id: ' ',
            testing: 'testing'
          }
        ],
        obj: {
          key: ' ',
          value: 'value'
        }
    }
    
    function setEmptyToNull(obj) {
        Object.keys(obj).forEach(key => {
            if (Array.isArray(obj[key])) {
                obj[key].map(o => {
                    if (typeof o === 'object') {
                        setEmptyToNull(o);
                    }
                })
            } else if(typeof obj[key] ==='string') {
              if(obj[key].trim() === '') {
                obj[key] = null;
              }  
            } else if(typeof obj[key] === 'object') {
              setEmptyToNull(obj[key]);
            }
        });
        return obj;
    }
    
    console.log(setEmptyToNull(objects));

    Now, if you want to use in your express application, then you can set that function in your custom middleware. It's will looks like this code below:

    app.use((req, res, next) => {
      if(req.body) {
        setEmptyToNull(req.body);
      };
      next();
    });
    

    After you set your custom middleware, now each value of key in your req.body, if it's ' ' then will be set to null.

    I hope it can help you.