asd
asd

Reputation: 57

Given user string input, how to check if object is in array

I'm trying to build a reference bot for discord that can be used to look up information (in this case, cars) and I'm having trouble with a concept. The user is capable of running a command to look up car information. The command the user gives might be $car1, and car1 will be stored in the variable inputCar. The array validCars holds all of the cars that can be looked up, and car1 is one of them. car1 is clearly not a string in this case but an object with multiple fields, but I need to figure out how to be able to look up information on the cars given a string input from the user. My question is twofold:

1) I know that the outer if statement won't work because inputCar is a string that the user entered, and the objects in the validCars array are objects. How can I properly check if what the user enters (in string format) matches the name of one of the objects?

2) Now assuming I can actually determine if the car exists in validCars given the user input, how can I access the fields (name, model, color) given the user input in order to print them?

This might not be the best way to accomplish what I'm trying to do, so any suggestions are appreciated.

var validCars = [car1, car2, car3, car4];

var car1 = {
  name:"Corvette Stringray",
  model:"2018",
  color:"red"
};

/***
 ***  car2, car3, and car4 all have the same setup as car1, just different values.
***/

// Scan each message (client.on is discord.js jargon)
client.on("message", (message) => {

  // Potential car name entered by user (message.content is discord.js jargon, 
  //it is just returning the string the user entered without the leading command prefix).
 // e.g. the value in inputCar might be "car1" if the user wanted to see info on car1.
  var inputCar = message.content.substr(1);

  // SHOULD check if this is an actual car. This if statement won't work because inputCar is a string,
  // and the values in validCars are not strings but objects.
  if (validCars.includes(inputCar) == true)
  {
    // Condition when car1 is entered (there would be other cases for the other cars)
    if (message.content == config.prefix + "car1")
    {
      // Print car1 info including name, model, and color
    } 
  }
  else 
  {
    // Invalid car was entered by user.
  }
});

Upvotes: 1

Views: 368

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138437

You might want to store the cars id with the car in a Map:

 const carByKey = new Map([
    ["car1", car1],
    /*...*/
 ]);

Then its quite easy to get the car:

  if(carByKey.has(message)){
    const car = carByKey.get(message);
    console.log(car.name);
    //...
  }

If you really want to get the javascripts variable that has the same name and is in global scope, thats possible with window/global (depending on your environment):

 if(message in window){
   const car = window[message];
 }

....But thats a very very bad idea.

Upvotes: 1

Related Questions