nodejs remove null from object 1

nodejs remove null from object

for(var key in req.body){
            if(req.body.hasOwnProperty(key)){
                if(req.body[key] == null) delete req.body[key];
            }
        }

Here is what the above code is Doing:
1. We’re creating a new object called `req.body`
2. We’re looping through the `req.body` object
3. If the `req.body` object has a property with the name of the key we’re looping through, we’re checking to see if the value of that property is null
4. If the value of that property is null, we’re deleting that property from the `req.body` object

Now, we can use the `req.body` object to update the database.

“`javascript
// Update the database
db.User.update(req.body, {
where: {
id: req.params.id
}
}).then(function(dbUser){
res.json(dbUser);
});
});
“`

## Delete a User

“`javascript
// Delete a user
app.delete(“/api/users/:id”, function(req, res){
db.User.destroy({
where: {
id: req.params.id
}
}).then(function(dbUser){
res.json(dbUser);
});
});
“`

## Create a Post

“`javascript
// Create a post
app.post(“/api/posts”, function(req, res){
db.Post.create(req.body).then(function(dbPost){
res.json(dbPost);
});
});
“`

## Read a Post

“`javascript
// Read a post
app.get(“/api/posts/:id”, function(req, res){
db.Post.findOne({
where: {
id: req.params.id
},
include: [db.User]
}).then(function(dbPost){
res.json(dbPost);
});
});
“`

## Update a Post

“`javascript
// Update a post
app.put(“/api/posts”, function(req, res){
db.Post.update(req.body, {
where: {
id: req.body.id
}
}).then(function(dbPost){
res.json(dbPost);
});
});
“`

## Delete a Post

“`javascript
// Delete a post
app.delete(“/api/posts/:id”, function(req, res){
db.Post.destroy({
where: {
id: req.params.id
}
}).then(function(dbPost){
res.json(dbPost);
});
});
“`

## Create a Comment

“`javascript
// Create a comment
app.post(“/api/comments”, function(req, res){
db.Comment.create(req.body).then(function(dbComment){
res.json(dbComment);
});
});
“`

## Read a Comment

“`javascript
// Read a comment
app.get(“/api/comments/:id”, function(req, res){
db.Comment.findOne({
where: {
id: req.params.id
},
include: [db.User]
}).then(function(dbComment){
res.json(dbComment);
});
});
“`

Similar Posts