Personal project - having issues finding an array in an object

Edit: I figured it out. I will leave this post up with this edit to show that yes, you should research your problem before asking the community. I feel foolish. Object.keys() will always return true with Array.isArray() in this case, because it always returns an array. Which is kind of its whole point. Thanks Google. Sorry freeCodeCamp community.

Ok, so…

I’m trying to iterate through character classes to find arrays and only log the charOption if it is an array instead of every property of the object.

My problem is that everything i put into the Array.isArray() returns true. So with the given code, with hitDice as the charOption, what i’d like is for it to log nothing, four times. If i were to switch the charOption to saveThrows, I’d like it to log three nothing and the array for saveThrows.

const classes = {
    Artificer: {
        charClass: 'Artificer',
        hitDice: '1d8',
        saveThrows: ['con', 'int'],
        skills: ['Arcana','History','Investigation','Medicine','Nature','Perception','Sleight of Hand']
    },
    Barbarian: {
        charClass: 'Barbarian',
        hitDice: '1d12',
        saveThrows: ['str', 'con'],
        skills: ['Animal Handling','Athletics','Intimidation','Nature','Perception','Survival']
    }
};

let classSelection = 'Barbarian';
let classOption = 'hitDice';

let classArr = Object.keys(classes);

for (i = 0; i < classArr.length; i++){
    if (classArr[i] == classSelection){
        for(j = 0; j < Object.keys(classes[classSelection]).length; j++){
            if (Object.keys(classes[classSelection])[j] == classOption && Array.isArray(Object.keys(classes[classSelection][classOption]))){
                console.log(classes[classSelection][classOption]);
            } else {
                console.log('nothing');
        }
    }
}

This code will log ‘nothing, 1d12, nothing, nothing’ when it should log ‘nothing’ four times.

Even when I log it outside of the code, it returns true for something that is not an array.

console.log(Array.isArray(Object.keys(classes[classSelection][classOption])))
//returns true

Please, if anyone can explain to me what is going on, or what I’m doing wrong, I would really appreciate it.

1 Like

I would take a look at what the value of classes[classSelection][classOption] is. In fact, you are already doing that, because you are using console.log to print it out.

if (Object.keys(classes[classSelection])[j] == classOption && Array.isArray(Object.keys(classes[classSelection][classOption]))){
  console.log(classes[classSelection][classOption]);
}

So you know that classes[classSelection][classOption] has the string value 1d12 when that if statement is true. So what happens when you pass that value into Object.keys? Once you figure that out you will see why Array.isArray() is returning true.

1 Like