Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
Discord js - Fetch Guild role list (array)

Trying to get roles from a discord server with discord.js

I started playing around with Discord bots using the discord.js library.

One of my objectives was to get the Guild roles in an array. I figured out a way to get it, but it is returning an array inside another array:

    const roles = client.guilds.cache.map(guild => {
        return guild.roles.cache.map(role=>role.name);
    });

    console.log(roles);

This is returning:

[ [ '@everyone', 'Demi God', 'Bot', 'God', 'Test' ] ]

I figured that there should be a better way? I figured I could also deconstruct the array but wanted to know if there was something I missed first.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There are a couple of ways to get a single array.

Using flat() to flatten the array:

const roles = client.guilds.cache
  .map((guild) => guild.roles.cache.map((role) => role.name))
  .flat();

Using flatMap() that will return a single collection of roles, so you'll still need to use map() to return an array of role names:

const roles = client.guilds.cache
  .flatMap((guild) => guild.roles.cache)
  .map((role) => role.name);

Using reduce():

const roles = client.guilds.cache.reduce(
  (acc, guild) => [...acc, ...guild.roles.cache.map((role) => role.name)],
  [],
);

Using push():

const roles = [];
client.guilds.cache.forEach((guild) => {
  roles.push(...guild.roles.cache.map((role) => role.name));
});

If you only want to use the role names, you can use any of these. If you want to use roles, not just their names, maybe flatMap() is the best option as it returns a single collection, similar to guild.roles.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!