JS Object behavior when trying to access a query related to Loopback

I work with the Loopback Framework, creating a web project. But I think that the question I am considering here has less to do with this, but with a general knowledge of Javascript / Node.JS.

In one part of the code, I do:

roleMapping.find({
        where: {
            principalType: 'USER',
            principalId: context.principals[0].id
        },
        include: 'role'
    }, function(err, roles){
        console.log(roles[0]);
        for (var i in roles)
        {
            if (roles[i].role.name === 'teamLeader' &&
                roles[i].groupId === context.modelId)
            {
                cb(null,true);
            }else {
                cb(null,false);
            }
        }
});

Good with this, but it does not work when trying to compare roles[i].role.name. So, I went to register what the object contained roles[i].

    { groupId: 1,
  id: 3,
  principalType: 'USER',
  principalId: 1,
  roleId: 2,
  role: 
   { id: 2,
     name: 'teamLeader',
     description: 'The leader(s) of a team',
     created: null,
     modified: null } }

Well, it's okay, but it still doesn't work, so I tried to print only the property role. And to my surprise:

{ [Function]
  update: [Function],
  destroy: [Function],
  create: [Function],
  build: [Function],
  _targetClass: 'Role' }

So, roledoes the property seem to be some kind of function? But how was it printed correctly before?

In the end, lost in my frustration, I tried var role = JSON.parse(JSON.stringify(roles[i]));

, .

JS ( , ), , - .

EDIT: , Framework, , .

+4
1

issue 1425, docs:

API Node.js toJSON(), JSON

, [...] JavaScript .

So you need to use

for (var i=0; i<roles.length; i++) {
    var x = roles[i].toJSON();
    cb(null, x.role.name === 'teamLeader'
             && x.groupId === context.modelId);
}
+6
source

All Articles