Skip to content
Advertisement

How do I get Info from an Array into a message?

I’m storing some info in an array like this:

array = [{ name:'name1', id:'id1' }, { name:'name2', id:'id2' }, { name:'name3', id:'id3'}];

I want to send a message from the bot back to the user with all the names in the array. How do I go about doing this?

Normally, I would use a for loop to cycle through for comparisons and such but I don’t want to send multiple messages. Just want one to respond back so I don’t think I’m supposed to use a for loop.

For clarification, this is what I would like the response from the Discord bot to look like:

“name1’s ID is id1, name2’s ID is id2, name3’s ID is id3”

Also the array can change. That’s something I realized I should probably let everyone know. So the array starts empty and then has random names pushed to it. So when someone uses the right command I want it to reply with every name in the array regardless of the length of the array.

Advertisement

Answer

There are multiple ways you can do this, and yes they involve some type of loop. A for loop is usually the fastest, but if there is only a few items, this will not matter. There is also Array.forEach() MDN and Array.reduce() MDN

using a forEach:

const array = [{name: "name1", id: "id1"}, {name: "name2", id: "id2"}, {name: "name3", id: "id3"}]
const itemCount = array.length;
const output = ''

array.forEach(item, idx => {
  output += `${item.name}'s ID is ${item.id}${idx < itemCount ? ', ' : ''}`
}

return output

using reduce

const array = [{name: "name1", id: "id1"}, {name: "name2", id: "id2"}, {name: "name3", id: "id3"}]
const itemCount = array.length;

return array.reduce((acc, item, idx) => {
  acc += `${item.name}'s ID is ${item.id}${idx < itemCount ? ', ' : ''}`
  return acc;
}, '');

for loop

const array = [{name: "name1", id: "id1"}, {name: "name2", id: "id2"}, {name: "name3", id: "id3"}]
const output = ''

for (let i = 0; i < array.length; i += 1) {
  const item = array[i];
  output += `${item.name}'s ID is ${item.id}${idx < itemCount ? ', ' : ''}`
}

return output;

There is probably a bug or two up there, but I hope you get the general idea. The ${idx < itemCount ? ', ' : ''} is just a messy way to not add a comma on the last item.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement