Home > Back-end >  How to assign two values for each element in an array discord.js
How to assign two values for each element in an array discord.js

Time:11-12

This is in discord.js. So I have three items each with a unique price (more items in the future).. Sending the name of the item for example "Item 1" should reply the price. How do I use the price variable in my code? I was thinking associative array but I think there's no associate array in JS.

  1. Item 1 = 100
  2. Item 2 = 300
  3. Item 3 = 500

I have this code:

const items = ["Item 1", "Item 2", "Item 3"];
const price = [100, 300, 500];

for (var i=0; i < items.length; i  ) {
if (message.content === items[i]) {
message.reply(PostPrice);
}
}

CodePudding user response:

I would use a Map, a built-in object in javascript

const items = new Map()
//create map
items.set("item 1",100)
items.set("item 2",300)
items.set("item 3",500)

//check if item exists
if(items.has(message.content.toLowerCase())){
  message.reply("price: " items.get(message.content.toLowerCase()))
}else{
  message.reply("this item doesnt exist");
}

CodePudding user response:

I would use json instead of arrays in this case

const items = {"item 1": { price: 100 }, "item 1": { price: 300 }, "item 1": { price: 500 }}

if(items[message.content.toLowerCase()) {
message.reply("price: " items[message.content.toLowerCase()]["price"])
} else {
message.reply("item doesnt exist")
}
  • Related