Search code examples
javascriptobjectauth0

Unusual javascript object notation


What does _raw, _json and ...userProfile mean as used in the below code ? This is from the auth0 example. Thank you!

router.get('/user', secured(), function (req, res, next)
{
    const { _raw, _json, ...userProfile } = req.user;
    console.log ('rec user ', req.user);
    //console.log ('user profile ', userProfile);
    res.render('user', {
        userProfile: JSON.stringify(userProfile, null, 2),
        title: 'Profile page'
    });
});

Solution

  • That notation is called Destructuring Assignment. Basically, req.user is an object with keys _raw, _json and other keys. With that syntax, you are reading directly the properties _raw and _json of the object and the rest of the object is saved into the userProfile variable. For that part, the Spread Syntax is used.

    Demo Example:

    const req = {
        user: {
          _raw: "raw",
          _json: "json",
          other1: "other1",
          other2: "other2"
        } 
    };
    
    const { _raw, _json, ...userProfile } = req.user;
    console.log("_raw is: ", _raw);
    console.log("_json is: ", _json);
    console.log("userProfile is: ", userProfile);
    .as-console {background-color:black !important; color:lime;}
    .as-console-wrapper {max-height:100% !important; top:0;}