I have an Array, project.users.
In this I have different things of the user defined.
Now I create a <p>
Element for each of the usernames. (Multiple showing only once).
Which is working.
Project.users can have the same user listed several times, but each time with a different assigned role.
What I want:
Show each username only once, as defined below, and show its associated user.role in the title attribut of the div.
If the username is existing multiple times (user.given_name and user.family_name
the same), it should also show the username only once, but (user.role always different in this case) should put both roles as the title in the div.
Example: username existing once:
username existing twice:
<% if (Array.isArray(project.users)) {
let usernames = project.users.map((user) => user.given_name " " user.family_name);
console.log(project.users);
for (username of new Set(usernames)) { %>
<div title="Here Comes The user.role">
<p class="home_projectdata_content"><%= username %></p>
</div>
<% }} %>
CodePudding user response:
So You can create an object which has all roles associated to the key (username) in this case.
And you can just loop below <p>
tag with roles[username]
<% if (Array.isArray(project.users)) {
let usernames = project.users.map((user) => user.given_name " " user.family_name);
const roles = {};
project.users.forEach((user) => {
const username = user.given_name " " user.family_name;
if (!roles[username]) roles[username] = [];
roles[username].push( user.role);
})
console.log(project.users);
for (username of new Set(usernames)) { %>
<div title="Here Comes The user.role">
<p class="home_projectdata_content"><%= username %></p>
<% for(role of roles[username]) { %>
<span><%= role %></span>
<% } %>
</div>
<% }} %>
CodePudding user response:
Firstly, I'm not sure what is the data source object you have (how is your fully JSON object or array data looks like). However, the idea you need to centralize the data source and transform it before rendering the UI.
For example, you might have projects object as below:
const projects = {
users: [
{
id: 1,
firstname: 'Ben',
lastname: 'Truong',
roles: {
moderator: true,
admin: true,
}
},
{
id: 2,
firstname: 'Ana',
lastname: 'Sarapova',
roles: {
moderator: true,
}
},
{
id: 3,
firstname: 'Carlos',
lastname: 'Hank',
roles: {
moderator: true,
}
},
]
};
const userInfo = [];
for (element of projects.users) {
// console.log(element.roles);
userInfo.push({
id: element.id,
fullName: element.firstname ' ' element.lastname,
userRoles: Object.keys(element.roles).toString(),
});
};
console.log(userInfo)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
and the output looks like
[[object Object] {
fullName: "Ben Truong",
id: 1,
userRoles: "moderator,admin"
}, [object Object] {
fullName: "Ana Sarapova",
id: 2,
userRoles: "moderator"
}, [object Object] {
fullName: "Carlos Hank",
id: 3,
userRoles: "moderator"
}]
Finally, you can map() through it as you want.