Access the second item in Collection [Map]

Viewed 621

I'm making a discord bot, and fetching some messages. I got this object

//This parameters changue every time i fetch
Collection(3) [Map] {
  '848689862764789770' => Message {...
  }
  '848689552410804234' => Message {...
  }
  '848689534485004319' => Message {...
  }

I can access the first and third entry using .first() and .last().

I've been trying to use Object.keys() but it returns undefined.

const mensajes = await message.channel.messages.fetch({ limit: 3 });
                
console.log(mensajes[Object.keys(mensajes)[1]])
2 Answers

Tip: .first() can take a parameter that will return the first x amount of entries you choose and will then convert the Collection into an Array. Do .first(2) - this will return the first 2 entries - and then access the 2nd element as you would with any other Array.

// Will return 2nd entry
<Collection>.first(2)[1]

Suggested Solution: You can also call .array() on the Collection to directly convert it into an Array.

// Also returns 2nd entry
<Collection>.array()[1]

<Collection> is a placeholder for your actual object

Learn more about working with Collections in This Guide

DiscordJS's docs has some information on this. You can transform this Collection utility class intro an array with a bunch of methods that exist for it, depending on what you need to access.

Then you can use the array, for example, to access the specific value.

// For values. Array.from(collection.values());

// For keys. Array.from(collection.keys());

// For [key, value] pairs. Array.from(collection);

Related