json - 如何从 JSON 文件访问用户选择的变量?(Node.js)
问题描述
这是交易:我正在尝试从 JSON 文件中的变量中获取数据,并使用不同的变量来命名。基本上,我想通过将“M83”替换为“Bands”来访问 MusicJSON.Bands.M83.length,否则,我必须将 JSON 文件中的每个变量都添加到我的代码中,这违背了我的目的。这是我的代码:
for(i = 0; i < MusicJSON.Bands.Names.length; i++) {
var Band = MusicJSON.Bands.Names[i]
NextMessage += "\n " + Band + MusicJSON.Bands.length + " songs"; // Right here
}
NextMessage += "**";
message.channel.send(`Here's a list of bands available on this server: \n ${NextMessage}`)
解决方案
我正在努力得到你想做的事。如果你MusicJSON.Bands
是这样的:
{
Names: ["1", "2", "3", "M83"],
1: ["song1", "song2", "song3"],
2: ["song1", "song2", "song3"],
3: ["song1", "song2", "song3"],
M83: ["Midnight City", "Wait", "Outro"]
}
你想得到每个乐队的长度,试试这个:
var next = "";
for (let name of MusicJSON.Bands.Names) { //automatically loop through the array
let number = MusicJSON.Bands[name].length; //access the object like MusicJSON.Bands["M83"]
next += `\n${name}: ${number} songs` //add the text
}
next += "**";
message.channel.send(`Here's a list of bands available on this server:\n${next}`);
另外,请记住,如果它们是对象中的键,则不需要存储名称,因为您可以像这样遍历键:
MusicJSON.Bands = {
M83: ["Midnight City", "Wait", "Outro"],
"System Of A Down": ["Toxicity", "Chic 'N' Stu", "Chop Suey"]
}
var names = Object.keys(MusicJSON.Bands).sort(), //create and array with the keys and sort it
next = "";
for (let band of names) {
next += `\n${band}: ${MusicJSON.Bands[band].length} songs`;
}
next += "**";
message.channel.send(`Here's a list of bands available on this server:\n${next}`);
我希望这是你想做的事情
推荐阅读
- android - 带有 ListView 的 Android RadioButton 组
- r - 如何将 LME4 输出提取到乳胶表?
- c++ - 创建一个函数以在最后向自身添加一个双向链表
- android - 如何以编程方式更改轮廓按钮图标?
- yocto - Yocto 构建失败,退出代码为“134”
- javascript - React useEffect,每次更新值时如何重新渲染
- python-3.x - Google Cloud 组设置 - 授权失败(python 应用)
- python - 将列的唯一值与列表中对应的另一列值进行比较
- kotlin - 如何在 Korge 中设置文本的格式?
- javascript - 有没有办法降低我必须请求大量 ID 的 HTTPS 请求