Miha Šušteršič Miha Šušteršič - 27 days ago 7
Javascript Question

Only assign property if defined

I have the following variable:

const quote = {
author: req.body.author,
quote: req.body.quote,
source: req.body.source,
updatedAt: Date.now(),
};


I only want to assign the values if they are defined. For example I can check for undefined with:

if(req.body.author === undefined) {
console.log('author undefined');
}


But how do I translate this to not assigning the value? Do I need to check afterwards and then remove the property if
undefined
?

Answer

Could you not just use default values and set them to null if the property is undefined in the post data?

//Unsure if you want the default value to have any meaning
//using null would likely achieve what you're asking.
var default_value = null;

const quote = {
    author: req.body.author || default_value,
    quote: req.body.quote || default_value,
    source: req.body.source || default_value,
    updatedAt: Date.now(),
};

If you really want to strip them, here's a basic loop you could use after.

for (var i in quote) {
       if (quote[i] == default_value) {
           //Unsure how this works with const... might have to change to var
           delete quote[i];
       }
   }

Alternatively you could iterate over the req.body object and avoid having to validate after the initial declaration.

var quote = {};

for (var i in req.body) {
    quote[i] = req.body[i];
}

Unsure if you would still want to validate against certain values in the req.body object so you could add a check for them being null/undefined

var quote = {};

for (var i in req.body) {

   //This will only declare the value on the quote object if the value
   //is not null or undefined. False could be a value you're after so
   //I avoided using the cleaner version of 'if (!req.body[i]) ...'
   if (req.body[i] !== null || req.body[i] !== undefined) { 
      quote[i] = req.body[i];
   }
}

You could even break that out into a nice reusable function (basic implementation below):

//Obj would be your post data
//bad_values would be an array of values you're not interested in.
function validatePOST (obj, bad_values) {

     var data = {};

     for (var i in obj) {

         //Check the value isn't in the array of bad values
         if (bad_values.indexOf(obj[i]) === -1) {

             data[i] = obj[i];
         }
     }

     //Return the validated object
     return data;
}

Now you could use this in all of your routes.

var quote = validatePOST(req.body, [null, undefined]);
Comments