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'
}
]
you can map the array into the fields like this:
separate fields
.addFields(
array.flatMap(user => [
{ name: 'ID', value: user.id, inline: true },
{ name: 'Name', value: user.user_name, inline: true },
{ name: 'Identifier', value: user.identifier, inline: true }
])
)
single fields
.addFields(
array.flatMap(user => [
{ name: 'User', value: `${id + username + identifier}`, inline: true },
])
)
Why flatMap()?
flatMap() is an inbuilt function in JavaScript which is used to flatten the input array element into a new array. This method first of all map every element with the help of mapping function, then flattens the input array element into a new array.
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] })