Search code examples
discord.js

DJS V14 - Pulling data from json based on given arguments


So I want to make a command that gives the relevant information about the "choice"/"args" that I provide, for example: /product item:"eggs" would provide the "name", "price" and "stock" of the item called "eggs", I tried to use a for loop and return the results to the console which it would only return the information for every item. How would I go about only getting it to display the one I choose?

{
 "stockItems": [
    {
      "name": "eggs",
      "price": 50,
      "stock": 100,
      "number": 1
    },
    {
      "name": "bacon",
      "price": 70,
      "stock": 10,
      "number": 2
    },
    {
      "name": "milk",
      "price": 20,
      "stock": 250,
      "number": 3
    }
  ]
}
const { readdirSync } = require("fs");
const { EmbedBuilder, SlashCommandBuilder, ApplicationCommandOptionType } = require("discord.js");
const { productInfo } = require("stock.json")

module.exports = {
  data: new SlashCommandBuilder()
    .setName("product")
    .setDescription("provides information about different products!")
    .addStringOption(option => 
                  option
                    .setName("product")
                    .setDescription("Type the product you want to view!"),
  async execute(interaction) {

let choice = interaction.options.getString("product")

for (let item of productInfo) {
 let stockInfo = `Name: ${item.name} Price: ${item.price} Stock: ${item.stock}`
                    
 if (item.number < 4) {
   console.log(stockInfo)
 }
}

The console would log it as this:

Name: eggs Price: 50 Stock: 100
Name: bacon Price: 70 Stock: 10
Name: milk Price: 20 Stock: 250

Solution

  • Only thing you really need to do is to add an if statement in the for loop that checks if your input matches with any of the items.

    for (let item of productInfo) {
     if (item.name === choice.toLowerCase()) {
      let stockInfo = `Name: ${item.name} Price: ${item.price} Stock: ${item.stock}`
      console.log(stockInfo);                    
      return;
     }
    }
    

    I also made choice lower case in the if statement incase a user inputs a capitalized word, always a good practice.