I’ve done some searching around and I found some posts on here but my code doesn’t want to work. Basically I’m making a discord bot and I want to select an object from a JSON file at random.
This is my command:
const UserData = require('../data/users.js'); const monster = require('../data/monsters.json'); module.exports = { name: 'battle', aliases: ['fight'], cooldown: 0, description: 'User fights against a monster alone or in group', execute(client, message, args) { let enemy = monster[Math.floor(Math.random() * monster.length)] UserData.findOne({ userID: message.author.id }, (error, userdata) => { if (error) console.log(error); if (!userdata) { return message.reply(`you don't have an account!`); } else { console.log(enemy); return message.channel.send(`${enemy} spawned!`); } }) } }
And this is my JSON file:
"1" : { "name": "Blue Slime", "hp": 20, "atk": 12, "def": 10, "spatk": 3, "spdef": 12, "spd": 100, "gold": 10, "xp": 50, "lvl": 1 }, "2": { "name": "Red slime", "hp": 20, "atk": 12, "def": 10, "spatk": 3, "spdef": 12, "spd": 100, "gold": 10, "xp": 50, "lvl": 1 }, "3": { "name": "Green slime", "hp": 20, "atk": 12, "def": 10, "spatk": 3, "spdef": 12, "spd": 100, "gold": 10, "xp": 50, "lvl": 1 } }
If I want put the objects in the command manually and then randomly select them it works and if instead of “monster.length” I put a number then it also works but I still get undefined if it should be 3. This way I also always get undefined in console log from monster.length. What am I doing wrong?
Advertisement
Answer
Your monsters.json
file contains an object and objects don’t have length
s. You can however convert it to an array, using Object.values()
that returns an array of the given object’s own enumerable property values.
Check out the snippet below:
let monsters = { 1: { name: 'Blue Slime', hp: 20, atk: 12, def: 10, spatk: 3, spdef: 12, spd: 100, gold: 10, xp: 50, lvl: 1, }, 2: { name: 'Red slime', hp: 20, atk: 12, def: 10, spatk: 3, spdef: 12, spd: 100, gold: 10, xp: 50, lvl: 1, }, 3: { name: 'Green slime', hp: 20, atk: 12, def: 10, spatk: 3, spdef: 12, spd: 100, gold: 10, xp: 50, lvl: 1, }, }; function randomObject(obj) { let arr = Object.values(obj); return arr[Math.floor(Math.random() * arr.length)]; } let enemy = randomObject(monsters); console.log(enemy);