Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select a random object(?) from a JSON file with Javascript?

In my Discord Bot that I am making, it needs to select a random object from a JSON file. My current code is this:

    function spawn(){
        if (randomNum === 24) return
        const name = names.randomNum
        const embed = new Discord.RichEmbed()
        .setTitle(`${name} has been found!`)
        .setColor(0x00AE86)
        .setThumbnail(`attachment://./sprites/${randomNum}.png`)
        .setTimestamp()
        .addField("Quick! Capture it with `>capture`!")
        msg.channel.send({embed});
    }

The JSON file looks like this:

{
    "311": "Blargon",
    "310": "Xryzoz",
    "303": "Noot",
    "279": "",
    "312": "Arragn",
    "35": "Qeud",
    ...
}

I want it to pick a random one of those, such as 303, and post it in a rich embed. What do I do from here?

like image 853
jackmerrill Avatar asked Apr 01 '26 09:04

jackmerrill


1 Answers

You can select a random name like this:

// Create array of object keys, ["311", "310", ...]
const keys = Object.keys(names)

// Generate random index based on number of keys
const randIndex = Math.floor(Math.random() * keys.length)

// Select a key from the array of keys using the random index
const randKey = keys[randIndex]

// Use the key to get the corresponding name from the "names" object
const name = names[randKey]

// ...
like image 128
Steve Holgado Avatar answered Apr 03 '26 23:04

Steve Holgado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!