简体   繁体   中英

how to reduce amount of if statements

Hi i am self learning MEAN stack and have a question regarding how to reduce the amount of if checks in my code.

Basically this works by the user fills in his/her settings page then clicks enter we then send the data to the server so we can update mongo.

the only way i have seemed to get this to work that allows the user to edit certain fields and not all is to ensure the data being sent to the server doesn't equal null but surely there has to be a better way then by running if statements for every field.

the code in question is this

        //user.username = req.body.username;

    if ( age != null) {

        user.age = age;

    }
    if ( bio != null) {

        user.bio = bio;

    }

    if ( location != null) {

        user.location = location;

    }

    if ( team != null) {

        user.team = team;

    }

    if ( tags != null) {

        user.tags = tags;

    }

    if ( email != null) {

        user.email = email;

    }

client side code

    $scope.savesettings = function(provider){
    var theUser = JSON.parse(localStorage.getItem("User-Data"));
    var user = theUser["_id"];
    var request = {};
    var request = {

        user: user,
        username: $scope.settings_username,
        email: $scope.settings_email,
        age: $scope.settings_age,
        location: $scope.settings_location,
        team: $scope.settings_team,
        bio:$scope.settings_bio,
        profilebanner: $scope.settings_profilebanner,
        avatar: $scope.settings_avatar

    };

    console.log(request);

    //send to server
    $http.put('api/social/updatesettings', request).success(function(response){

        alertify.success("Your settings have been successfully saved.");

            localStorage.clear();
            localStorage.setItem('User-Data', JSON.stringify(response));



    }).error(function(error){

        alertify.error("Hmmm an issue has occured.");

     });


};

server code

var User = require('../../datasets/userModel');

module.exports.updatesettings = function(req, res){

    var age = req.body.age;
    var bio = req.body.bio;
    var location = req.body.location;
    var team = req.body.team;
    var tags = req.body.tags;
    var email = req.body.email;
    var profilebanner = req.body.profilebanner;
    var avatar = req.body.avatar;

User.findOne({_id: req.body.user}, function (err, user){


    //user.username = req.body.username;

    if ( age != null) {

        user.age = age;

    }
    if ( bio != null) {

        user.bio = bio;

    }

    if ( location != null) {

        user.location = location;

    }

    if ( team != null) {

        user.team = team;

    }

    if ( tags != null) {

        user.tags = tags;

    }

    if ( email != null) {

        user.email = email;

    }

    user.save(function(err){

        if (err){
            console.log(err);
            res.status(500).send();
            //res.json(user);
        } else {
            console.log("success");
             res.json(user);
        }
    })
});

};

Consider using Object.assign . It merges two or more objects, with the latter ones taking precedence. The following assumes data is an object containing your age , bio etc. and user is, well... your user object.

var results = Object.assign({}, user, data);

There are polyfills for this, and if you happen to use jQuery, $.extend mostly does the same job.

You can add all attributes to user object.

var user = {
   age: age,
   bio: bio,
   location: location
}

And then delete keys for null values.

for (var key in user) {
   if (user[key] === null) {
      delete user[key];
   }
}

How about a function into which you pass an array of variables and use some to see if any of them are null .

function isComplete(args) {
  return !args.some(function(el) {
    return el === null;
  });
}

var age = null;
var bio = 'Something';
var location = null;

isComplete([age, bio, location]); // false

The if s are not the problem. The problem is that you're showing fields to the user that they are not supposed to see, so the problem is in the presentation layer.

Fixing that series of if s is just like sweeping dust under the carpet, it seems like you want roles for your users, so make that clear and understandable in your code.

You could fix this with server side generated HTML, something like this (syntax might be wrong but I hope you get the point):

<% if (user.canSetTeam()) { %>
  <input type="text" name="team" />
<% } %>

So in your HTML you will have just the right fields.

Have a look at http://expressjs.com/en/guide/using-template-engines.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM