如何使用 Javascript 从 JSON 文件中选择随机对象(?)?

jac*_*ill 3 javascript node.js discord discord.js

在我正在制作的 Discord Bot 中,它需要从 JSON 文件中选择一个随机对象。我当前的代码是这样的:

    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});
    }
Run Code Online (Sandbox Code Playgroud)

JSON 文件如下所示:

{
    "311": "Blargon",
    "310": "Xryzoz",
    "303": "Noot",
    "279": "",
    "312": "Arragn",
    "35": "Qeud",
    ...
}
Run Code Online (Sandbox Code Playgroud)

我希望它随机选择其中一个,例如303,并将其发布到丰富的嵌入中。从这里我该怎么办?

Ste*_*ado 7

您可以选择一个随机名称,如下所示:

// 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]

// ...
Run Code Online (Sandbox Code Playgroud)