[英]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.
在我的情况下,我正在制作一个Discord机器人,每个服务器都有自己的设置。 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: conf.json:
{
"Settings": [
"358262452343013386" {
"prefix": "$",
"Admins": [
"155444308395294720"
],
"NotificationChannel": "358772856282284033",
"robotpieces": []
}
]
}
What I want to be able to do in my bot.js: 我想在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. 编辑:我知道以下JSON是无效的,但我想要一个可以给出相同结果的解决方案。
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: 除了您发布的JSON无效的事实之外,您还可以将服务器设置存储为对象而不是array ,并且访问就像您尝试执行的操作:
{
"Settings": {
"358262452343013386": {
"prefix": "$",
"Admins": [
"155444308395294720"
],
"NotificationChannel": "358772856282284033",
"robotpieces": []
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.