Home > Software engineering >  how to send this array as one embed message in discord.js (javascript)
how to send this array as one embed message in discord.js (javascript)

Time:05-28

I want to send this data as one embed message and I don't know how many of these we have.

I tried to do like this :

            let list = hk;
            var id = "";
            var username = "";
            var identifier = ""
            for (var i = 0; i < list.length; i  ) {
                id  = list[i].id   '\n';
                username  = list[i].user_name   '\n';
                identifier  = list[i].identifier   '\n';

            }
                const pListEmbed = new Discord.MessageEmbed()
                    .setColor('#03fc41')
                    .setTitle('Connected')
                    .setDescription(`Total : ${list.length}`)
                    .setThumbnail(config.logo)
                    .addFields({ name: 'ID', value: id, inline: true }, { name: 'Name', value: username, inline: true }, { name: 'Identifier', value: identifier, inline: true },

                    )
                    .setTimestamp(new Date())
                    .setFooter('Used by: '   message.author.tag, `${config.SERVER_LOGO}`);

                message.channel.send(pListEmbed);
        });

but it sends several separate embed messages, each containing the data and hk is this array that we don't know how many of the data we have

array :

    {
  id: '46892319372',
  user_name: 'testerOne',
  identifier: '20202'
}
{
  id: '15243879678',
  user_name: 'testerTwo',
  identifier: '20201'
}
{
  id: '02857428679',
  user_name: 'testerThree',
  identifier: '20203'
}
{
  id: '65284759703',
  user_name: 'testerFour',
  identifier: '20204'
}

CodePudding user response:

Simply use .forEach, that will loop over every single element and use the "addFields" method ->

// .setThumbnail()..
list.forEach(user => pListEmbed.addFields(
  { name: 'ID', value: user.id, inline: true },
  { name: 'Name', value: user.user_name, inline: true },
  { name: 'Identifier', value: user.identifier, inline: true }
))

message.reply({ embeds : [pListEmbed] })

CodePudding user response:

you can map the array into the fields like this:

.addFields(list.map(item => {
  { name: 'ID', value: item.id, inline: true },
  { name: 'Name', value: item.user_name, inline: true },
  { name: 'Identifier', value: item.identifier, inline: true }
}))

Why map()?

map() method is used to iterate over an array and calling function on every element of the array which is perfect for this case to create fields based on each object in the array and its values.

  • Related