Mark
Mark

Reputation: 49

How can I access user-selected variable from a JSON file? (Node.js)

Here's the deal: I'm trying to get data from a variable in a JSON file by name with a different variable. Basically, I want to access MusicJSON.Bands.M83.length by replacing the "M83" with "Bands", else, I'd have to add every single variable in the JSON file into my code, which defeats the purpose to me. Here's my code:

    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}`)

Upvotes: 0

Views: 40

Answers (1)

Federico Grandi
Federico Grandi

Reputation: 6816

I'm struggling to get what you want to do. If your MusicJSON.Bands is like this:

{
  Names: ["1", "2", "3", "M83"],
  1: ["song1", "song2", "song3"],
  2: ["song1", "song2", "song3"],
  3: ["song1", "song2", "song3"],
  M83: ["Midnight City", "Wait", "Outro"]
}

And you want to get the length of every band, try this:

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}`);

Also, keep in mind that you don't need to store the names if they're the keys in your object, because you can loop through the keys like this:

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}`);

I hope this is the thing you wanted to do

Upvotes: 1

Related Questions