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

14,222

Solution 1

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]

// ...

Solution 2

const jsonData = {
    "311": "Blargon",
    "310": "Xryzoz",
    "303": "Noot",
    "279": "",
    "312": "Arragn",
    "35": "Qeud",
}
const values = Object.values(jsonData)

const randomValue = values[parseInt(Math.random() * values.length)]

console.log(randomValue)

Share:
14,222
jackmerrill
Author by

jackmerrill

I'm a fullstack developer and graphic designer!

Updated on June 22, 2022

Comments

  • jackmerrill
    jackmerrill about 2 years

    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?

  • jackmerrill
    jackmerrill about 6 years
    I tried what you did there, and I got this error: TypeError: xobj.overrideMimeType is not a function
  • Rohit Nandi
    Rohit Nandi about 6 years
    It works for me, I tried with python and nodeJs servers, in Chrome,IE. Can you give some inputs like which server, browser and software versions you are using? I got a post on similar problem, posted yesterday stackoverflow.com/questions/49675273/…
  • Rohit Nandi
    Rohit Nandi about 6 years
    Info Across the internet: If using IE, It is only supported in IE11 and later. You can omit that line, it will still work, with the default server provided MIME type eg. 'text/plain'
  • Rohit Nandi
    Rohit Nandi about 6 years
    One more alternative you can safe guard it by using if (xobj.overrideMimeType) { xobj.overrideMimeType( 'application/json' ); }