Search code examples
javascriptecmascript-6object-literal

Is there an easier way to assign this variable with object destructuring?


const user = new db.User({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        password: req.body.password,
        email: req.body.email,
        dateCreated: req.body.dateCreated
    })

I know there's a way to assign values to an object by giving the attributes the same name as their source but I'm not sure how this would work.


Solution

  • You could deconstruct all of these values above to simplify it:

    const { firstName, lastName, password, email, dateCreated } = req.body

    Then all you would need to do is the following:

    const user = new db.User({
        firstName,
        lastName,
        password,
        email,
        dateCreated,
    })