简体   繁体   中英

JavaScript / JSON - Access array element using a key name as index

I want to be able to access an array element by using a unique key name instead of a numeric index. In my situation, I'm making a Discord bot and each servers have their own settings. When someone sends a message on a server, I want to access some of this server's settings (such as a message prefix). IMPORTANT: Right now, the only way I can do this is looping through all the servers that the bot is in, which in long-term, could slow it down if there's hundreds of active servers sending messages. So looping through all the servers is already being done right now, but I want a direct way without having to do this.

conf.json:

{
    "Settings": [
         "358262452343013386" {
             "prefix": "$",
             "Admins": [
                 "155444308395294720"
             ],
             "NotificationChannel": "358772856282284033",
             "robotpieces": []
         }
    ]
}

What I want to be able to do in my bot.js:

console.log(conf.Settings[message.guild.id].prefix); // outputs the prefix
// message.guild.id is the id of the server, which in this case, would translate to this:
console.log(conf.Settings["358262452343013386"].prefix) // outputs '$'

Any ideas of how I can achieve a similar goal WITHOUT having to loop through all of the array?

EDIT: I know the following JSON is invalid, but I want a solution which would give the same result.

Aside from the fact that the JSON you posted is invalid, you could store the server settings as an object rather than an array , and access is just like you are trying to:

{
    "Settings": {
         "358262452343013386": {
             "prefix": "$",
             "Admins": [
                 "155444308395294720"
             ],
             "NotificationChannel": "358772856282284033",
             "robotpieces": []
         }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM