I have this code to loop through a collection of roles which works.
const guild = client.guilds.cache.get('827888294100074516');
await guild.roles.fetch().then(roles => {
for(const role of roles) {
console.log(role[1].id + ' ' + role[1].name);
}
});
but why do I have to refer to the role as role[1] before it works?
Because when iterating over a javascript Map (which the discord.js Collection is derived from) with for const, the value you get is a 2-length array where the 0th element is the key and the 1st element is the value. Here's an example:
await guild.roles.fetch().then(roles => {
for (const role of roles) {
console.log(role[0]); // This will give you the role id
console.log(role[1]); // This will give you the actual role object, like you've used in your code
}
}
As for rewriting your existing code so that you don't have to use [1] every time to refer to role, you can use array destructuring like this:
await guild.roles.fetch().then(roles => {
for (const [id, role] of roles) {
// `id` is the role id and `role` is the actual role object
console.log(role.id + " " + role.name);
}
}
You can also use .forEach(), like:
await guild.roles.fetch().then(roles => {
roles.forEach((role, id) => {
// `id` is the role id and `role` is the actual role object
console.log(role.id + " " + role.name);
});
}
For a full list of stuff you can do with javascript Maps, here's the link to the MDN docs and for a full list of stuff that you can do with discord.js Collections (which includes the stuff you can do with javascript Maps), here's the link to the discord.js Collection docs.
This is just a personal favour of using a for loop. The error in your code is your only fetching the second position on that map(as you count from 0).
const guild = client.guilds.cache.get('827888294100074516');
guild.roles.fetch().then(roles =>{
for(var i in roles){
var role = roles[i];
console.log(`Role id: ${role.id} Role name: ${role.name}`)
}
})
The guild is the guild you are targeting to fetch. The fetch functions fetches all the roles. The .then functions bracket is all the events that happen after the fetch is complete. The for loop just goes for all the positions inside of that map and then console.logs the data(ids and names)