Jorre
Jorre

Reputation: 17581

Check if property is not undefined

I'm building a node+express app and I'm filling an object with JSON that's submitted from a form in the frontend. This works, unless I leave a field empty in the form so that e.g. req.body.address.street is empty/undefined.

This will result in the error:

TypeError: Cannot read property 'street' of undefined

var b = new Business({
        name: req.body.name,
        phone: req.body.phone,
        address: {
            street: req.body.address.street,
            postalCode: req.body.address.postalCode,
            city: req.body.address.city
        },
        owner: {
            email: req.body.owner.email,
            password: req.body.owner.password
        }
    });

My question is how I can best prevent my app from crashing when values are empty. I would like to avoid manually checking each and every property in my app against undefined.

I'm wondering what the best practice is for this common issue.

Upvotes: 1

Views: 95

Answers (2)

Buzinas
Buzinas

Reputation: 11725

I don't know if you use jQuery in your project, but if you do, you can create a mask:

// creating your object mask
var req = {
    body: {
        name: '',
        phone: '',
        address: {
            street: '',
            postalCode: '',
            city: ''
        },
        owner: {
            email: '',
            password: ''
        }
    }
}

And then, you simply use the jQuery "extend" method (req2 is your submmited object):

$.extend(true, req, req2);

I've create this fiddle for you!

-

Update

Nothing related to your question, but I've just noticed that you're passing an object with a similar structure of req.body to the Business class. However, there is no need to copy property by property manually - you can make, for example, a simple copy of req.body to pass as parameter:

var b = new Business($.extend({}, req.body));

or

var b = new Business(JSON.parse(JSON.stringify(req.body)));

Upvotes: 1

Matt
Matt

Reputation: 75317

You can't, really. You have two options;

Use a try/ catch:

try {
    var b = new Business({
        // 
    });
} catch (e) {
    // Something wasn't provided.
}

... or you can define a helper function:

function get(path, obj) {
    path = path.split('.');
    path.shift(); // Remove "req".

    while (path.length && obj.hasOwnProperty(path[0])) {
        obj = obj[path.shift()];
    }

    return !path.length ? obj : null;
}

... you could then replace your use of req.body.address.street etc. with get('req.body.address.street', req).

See a demo here; http://jsfiddle.net/W8YaB/

Upvotes: 0

Related Questions