Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Discord.js – Correct use of: for (const guild of client.guilds.cache)? without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
I have (what probably is a very simple) question:
I have been using
client.guilds.cache.map((guild) => {
and so on, and that works fine but I know that as the elements increase, a for loop is more efficient.
I tried:
for (const guild of client.guilds.cache) { console.log(guild.name)
but that returns: undefined
If I console.log(guild) I get the guild info in the console and name is absolutely a part of is
From console:
[ '', Guild { members: GuildMemberManager { cacheType: [class Collection extends Collection], cache: [Collection [Map]], guild: [Circular] }, channels: GuildChannelManager { cacheType: [class Collection extends Collection], cache: [Collection [Map]], guild: [Circular] }, roles: RoleManager { cacheType: [class Collection extends Collection], cache: [Collection [Map]], guild: [Circular] }, presences: PresenceManager { cacheType: [class Collection extends Collection], cache: [Collection [Map]] }, voiceStates: VoiceStateManager { cacheType: [class Collection extends Collection], cache: Collection [Map] {}, guild: [Circular] }, deleted: false, available: true, id: '', shardID: 0, name: "GA's Testingserver!", icon: '11a80a894a50cafd46c95451ed83f939', splash: null, discoverySplash: null, region: 'europe', memberCount: 5, large: false, features: [], applicationID: null, afkTimeout: 300, afkChannelID: null, systemChannelID: '', embedEnabled: undefined, premiumTier: 0, premiumSubscriptionCount: 0, verificationLevel: 'NONE', explicitContentFilter: 'DISABLED', mfaLevel: 0, joinedTimestamp: 1598456514616, defaultMessageNotifications: 'ALL', systemChannelFlags: SystemChannelFlags { bitfield: 0 }, maximumMembers: 100000, maximumPresences: null, approximateMemberCount: null, approximatePresenceCount: null, vanityURLCode: null, vanityURLUses: null, description: null, banner: null, rulesChannelID: null, publicUpdatesChannelID: null, preferredLocale: 'en-US', ownerID: '', emojis: GuildEmojiManager { cacheType: [class Collection extends Collection], cache: [Collection [Map]], guild: [Circular] } } ]
For some reason, I can’t wrap my head around this…
Answer
According to discord.js documentation, guild.cache
has type collection
not array
.
You can iterate over each guild
in the collection:
client.guilds.cache.each(guild => { console.log(guild.name); });
Or you can iterate over each guild
in the array:
for (const guild of client.guilds.cache.array()) { console.log(guild.name); }
We are here to answer your question about Discord.js – Correct use of: for (const guild of client.guilds.cache)? - If you find the proper solution, please don't forgot to share this with your team members.