简体   繁体   中英

Custom Sort array objects in discord.js embed

Here's my code

const Command = require("../../structures/command");
const { MessageEmbed } = require("discord.js");
const data = require("../../data/Data.json");

module.exports = class B extends Command {
  constructor(client) {
    super(client, {
      name: "b",
      aliases: ["B"],
      category: "",
    });
  }

  async run(message, args, server) {
    const Name = args[0];

    const filtered = data.filter((b) => b.name === Name);

    const [
      { name, region, location, cooldown, reqs, rewards, thirdRewards, teams },
    ] = filtered;

    const Team_1_pokesName = teams[[0]].map((t) => t.name).join("\n");
    const Team_1_pokesMove = teams[[0]].map((t) => t.moves).join("\n");
    const Team_2_pokesName = teams[[1]].map((t) => t.name).join("\n");
    const Team_2_pokesMove = teams[[1]].map((t) => t.moves).join("\n");
    const embed = new MessageEmbed()
      .setAuthor(name)
      .setColor("RANDOM")
      .addField("Region", `${region}`, true)
      .addField("Location", `${location}`, true)
      .addField("Cooldown", `${cooldown}`)
      .addField(
        "Requirement/s",
        `${JSON.stringify(reqs).replace(/[\[\]"]+/g, "")}`
      )
      .addField("Team #1", `${Team_1_pokesName}\n${Team_1_pokesMove}`, true)
      .addField("Team #2", `${Team_2_pokesName}\n${Team_2_pokesMove}`, true)
      // .addField("Team #3", teams[[3]], true)
      // .addField("Team #4", teams[[4]], true)  // .... and so on
      .addField(
        "Rewards",
        `${JSON.stringify(rewards).replace(/[\[\]"]+/g, "")}`
      )
      .addField(
        "Third Rewards",
        `${JSON.stringify(thirdRewards).replace(/[\[\]"]+/g, "")}`
      );
    message.channel.send(embed);
  }
};

Currently, it shows something like this . So, is it possible to add teams inside the bracket for each of them? Here's an example. . And I'm getting an error while adding the arg in lowercase and Team_2_pokesMove or Team_3_pokesMove undefined for the ones which don't have 2nd or 3rd object.

Here's an example of the Data.json Click here

First, instead of .filter() you could use the .find() method which returns the first found item in an array. So, it either returns the found object, or undefined ; this way you only need to destructure the object.

If you want to accept case-insensitive args, you can use .toLowerCase() to convert both the user submitted argument and name to lowercase and compare them that way.

You could use .addFields() to add an array of fields to the embed and iterate over the teams to create a new field for every single team. By iterating over them, you don't have to create new Team_1_pokesName -like variables for every team, it will work with any number of teams received from the JSON file.

For the fields' name you can use the indices (plus one), and for the value you can loop over your data and create a new string using template literals and joining the moves .

Also, instead of that ugly regex, you could just use the built-in .join() method to create a string from the array elements.

Check out the working code below:

module.exports = class B extends Command {
  constructor(client) {
    super(client, {
      name: 'b',
      aliases: ['B'],
      category: '',
    });
  }

  async run(message, args, server) {
    const found = data.find((d) => d.name.toLowerCase() === args[0].toLowerCase());

    if (!found)
      return message.channel.send(`Can't find anything with the name of _"${args[0]}"_`);

    const {
      cooldown,
      location,
      name,
      region,
      reqs,
      rewards,
      teams,
      thirdRewards,
    } = found;

    const embed = new MessageEmbed()
      .setAuthor(name)
      .setColor('RANDOM')
      .addField('Region', region, true)
      .addField('Location', location, true)
      .addField('Cooldown', cooldown)
      .addField('Requirement/s', reqs.join(', '))
      .addFields(
        teams.map((team, i) => ({
          inline: true,
          name: `Team #${i + 1}`,
          value: team
            .map((e) => `${e.name} (${e.moves.join(', ')})`)
            .join('\n'),
        })),
      )
      .addField('Rewards', rewards.join(', '))
      .addField('Third Rewards', thirdRewards.join(', '));
    message.channel.send(embed);
  }
};

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM