Search code examples
javascriptnode.jsdiscorddiscord.jsbots

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.


Solution

  • 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.