Search code examples
javascriptnode.jsflash-message

How to flash all the properties of an object in Node


I'm using Express with connect-flash.

In validating a form, I am currently using this and it works:

req.flash('old_name', object.name)
req.flash('old_email', object.email)
req.flash('old_age', object.age)

How can I iterate through the properties of the object and flash for each? I'd like to be able to reuse the solution to validate other objects.

Something like:

for (let property in object) {
    req.flash('old_' + property, object[property])
}

console.log(object):

{
    _id: 'sjdfoiasdhfaushdfhweuhu',
    name: 'Harry',
    email: '[email protected]',
    age: 45
}

Solution

  • I figured this out. I think this solution will be pretty specific to Express.js with mongoose:

    for (var prop in object._doc) {
        if (object._doc.hasOwnProperty(prop)) {
            req.flash('old_' + prop, object._doc[prop])
        }
    }