Reputation: 15
so i want to show all of groups that user have when logged in. But i just got 1 value only. I'm still newbie using node js
so here the code :
var data = { id: user.id_panel_users, username: user.username, role: user.role, groups: user.groups }
var [group] = await modelGroup.getUserGroup(data.id)
for(let i=0;i<group.length;i++){
data.groups = group[i].group_name;
}
console.log(group, data.groups)
// data.toString();
console.log("serialize user: ", data)
done(null, data);
here the result :
[
TextRow { group_name: 'add_url_premium' },
TextRow { group_name: 'add_url_regular' }
] add_url_regular
serialize user: {
id: 77,
username: '082122735123',
role: 2,
groups: 'add_url_regular'
}
Upvotes: 0
Views: 1482
Reputation: 148
data.groups
needs to be an array
. What you are doing is instead of appending group_name
to data.groups
, you are assigning the string to it. So, instead of :
for(let i=0;i<group.length;i++){
data.groups = group[i].group_name;
}
you should use:
for(let i=0;i<group.length;i++){
data.groups.push(group[i].group_name);
}
Also, var
is an old way of declaring variables in javascript. If you are new, I would suggest using let/const
Upvotes: 1
Reputation: 2342
The main problem that I can see is in the for
loop:
for (let i = 0; i < group.length; i++) {
data.groups = group[i].group_name;
}
Every time, you are assigning the group name to the data.groups
field. This changes the type from an array
to a string
and overwrites the previous value every time.
You should instead be using the Array.prototype.push
function to add the group to the end of the array:
for (let i = 0; i < group.length; i++) {
data.groups.push(group[i].group_name);
}
There is a cleaner way of doing this using the map
function: it loops through an array and applies a function to each item, replacing that item in the array with the value that the function returned. In your case, your code would become:
let data = { id: user.id_panel_users, username: user.username, role: user.role, groups: user.groups }
let [group] = await modelGroup.getUserGroup(data.id);
data.groups = group.map(g => g.group_name);
I would also recommend that you use semi-colons ;
at the end of all statements, and that you try to be consistent in your use of let
/const
and var
.
Upvotes: 1