首页 > 解决方案 > 如何从 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}`)

标签: jsonnode.jsdiscord.js

解决方案


我正在努力得到你想做的事。如果你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}`);

我希望这是你想做的事情


推荐阅读