Steven Webster
Steven Webster

Reputation: 308

Cannot access object's properties - objects

I'm working on a discord bot of mine and I was making a "help" command. I first had a commands array and if they wanted help on a specific command I had to add more lines of code than I want to. I was wondering if I could do put an object inside of my object like this:

const commands1 = {
    coinflip: {
        usage: prefix + "coinflip",
        description: `Flip a coin then guess what it landed on.`
    }
    diceroll: {
        usage: prefix + "diceroll (number)",
        description: `Roll a die and guess what it lands on`
    }
};

Or would I have to do something else, because when I do

for(var name in commands1){
    embed.addField("Command:", name)
}

this will list all the commands available. However I can't access the usage or description, I tried this by doing this:

.addField("Usage:", name.usage)
.addField("Description:", name.description)

(it says undefined) Am I accessing it wrong or can I not put objects in objects. Sorry, I'm relatively new to this :) Thanks.

Upvotes: 0

Views: 86

Answers (3)

Kasem O
Kasem O

Reputation: 64

Don't worry about being new, we all started somewhere.

Your newbie questions are probably better than mine were!

const commands1 = {
    coinflip: {
        usage: prefix + "coinflip",
        description: `Flip a coin then guess what it landed on.`
    },
/* Added a missing , above */ 
    diceroll: {
        usage: prefix + "diceroll (number)",
        description: `Roll a die and guess what it lands on`
    }
};

for(var name in commands1){
    embed.addField("Command:", name);
    console.log(commands1[name].usage);
    console.log(commands1[name].description); /* You can Use your index to directly access the object thru the parent object. */ 
}

Upvotes: 0

Jai
Jai

Reputation: 74738

You are using for...in loop, which iterates over the indexes of the array. But the real scenario is you have object. So, in this case i would suggest you this:

const commands1 = {
    coinflip: {
        usage: prefix + "coinflip",
        description: `Flip a coin then guess what it landed on.`
    }
    diceroll: {
        usage: prefix + "diceroll (number)",
        description: `Roll a die and guess what it lands on`
    }
};

const keys = Object.keys(commands1); // #Output : ["coinflip", "diceroll"]

for(let key of keys){
   embed.addField("Command:", commands1[key].usage);
}

Upvotes: 1

Steven Webster
Steven Webster

Reputation: 308

I found out that name. is literal and it thinks I'm trying to access commands1.name when I wanted commands1.coinflip. So I fixed it by doing this

console.log(commands1.coinflip.usage)

Upvotes: 2

Related Questions