Home > Back-end >  Node.js - Access items from array based on user input
Node.js - Access items from array based on user input

Time:08-15

could someone please point out what I do wrong? The program is supposed to allow me to use a discord command: C!send quote (number) (username) to select one specific quote from the list and send it as a message.

msg.channel.send(`${quotes.quote[args[1]]}`);

This line gives me the most trouble. Everything else works, but when I type the command (C!send quote 17 Username) program crashes and I get an error:
msg.channel.send(${quotes.quote[args[1]]});
TypeError: Cannot read properties of undefined (reading '17')

const Discord = require('discord.js');
require('dotenv').config();
const client = new Discord.Client();

    const quotes = [
        {
            id: "1",
            quote: "This is quote 1"
        },
        {   
            id: "2",
            quote: "This is quote 2"
        },
        {
            id: "3",
            quote: "This is quote 3"
        },
        {
            id: "4",
            quote: "This is quote 4"
        },
        {
            id: "5",
            quote: "This is quote 5"
        },
];

    client.on('message', (msg) => {
        if (msg.content.startsWith("C!send")) {
            let messageArray = msg.content.split(" ");
            let args = messageArray.slice(1)
            if (!args[0]) {
              return msg.channel.send("Error, missing argument 1");         
            } else if (args[0] === "quote") {
                if (!isNaN(args[1])) {
                   if (args[2] === undefined) {
                       return msg.channel.send("Erorr, missing argument 3");
                   } else {
                       msg.channel.send(`${quotes.quote[args[1]]}`); //This is where the program crashes
                   }
                } else {
                    return msg.channel.send("Error, argument 2 needs to be a number!");
                }
        }

}

This line gives me th

CodePudding user response:

In your code quotes is an array. In ${quotes.quote[args[1]]} you're trying to access quote property of quotes which does not exist.

Try this instead:

`${quotes.find(i => i.id === args[1]).quote}`

If you're not checking whether quote exists beforehand:

`${quotes.find(i => i.id === args[1])?.quote || "Quote not found"}`
  • Related