javascriptobjectdestructuringspread-syntaxrest-parameters

JavaScript object shorthands


I have this clunky code here and hope there is any way to shorten this. By the way, "req.query" is my query object from an nodejs express server.

    const q = req.query

    User.insertOne({
        firstName: q.firstName,
        lastName: q.lastName,
        bestFriend: q.bestFriend,
        hobbies: q.hobbies,
        address: {
            street: q.address.street,
            number: q.address.number,
            plz: q.address.plz,
            city: q.address.city,
            country: q.address.country,
        },
        contact: {
            telephone: q.contact.telephone,
            email: q.contact.email,
        },
    })

My first solution was - as you can see - to replace req.query with q, but this does not seem to be enough.

Maybe you could do this with the "with" statement, but i haven't used it before and I've heard that you shouldn't implement it (don't know why....).


Solution

  • By reading your title I understood you want to use ES6 object property shorthand. To achieve that in your current setup you would also need to use object destructuring, here's the code:

    //Object destructuring:
    const { firstName, lastName, bestFriend, hobbies } = req.query;
    const { street, number, plz, city, country } = req.query.address;
    const { telephone, email } = req.query.contact;
    
    //Using the ES6 object property shorthand:
        User.insertOne({
            firstName,
            lastName,
            bestFriend,
            hobbies,
            address: {
                street,
                number,
                plz,
                city,
                country,
            },
            contact: {
                telephone,
                email,
            },
        })