Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

A Javascript question (Objects in a loop).

Hi guys!

Just wanna ask for help on my code i got stuck on how to implement a Object inside a For Loop.

So I have this to do's:

  1. create Object containing bio of a user.
  2. Asked Name, Aged, Sex.

So far this is my code:

var userQuestions = [
    "Name",
    "Age",
    "Sex"
];

var userDetails = {
    user : '',
    age : 0,
    sex : ''
}

console.log(userDetails);


    for (var i = 0; i < userQuestions.length; i+=1){
        var question = userQuestions[i];
        var answer = prompt(question);

        if( answer ) {
            //HOW TO ADD THE ANSWERS TO MY OBJECTS KEYS userDetails.
        }

    }

As you can see I can figure out how to add the Users Answer back to the Object named usersDetails. I was thinking just to update the userDetails.name = 'User Answer'. But I can think on how to use the objects index if its possible.

I appreciate for your help!

Thanks,

Owa

1 Answer

Hi Owa,

This is pretty simple to implement, with one small change! Did you notice that the questions in your array are very similar to the object properties that you want to use? The only exceptions are that you have a question 'Name' and the corresponding property is 'user', and of course your object properties are lower case.

If you create a third variable, key, which you set to be equal to the lower-case version of your question, then you can then use this to access the corresponding property in your object:

for (var i = 0; i < userQuestions.length; i+=1){
    var question = userQuestions[i];
    var answer = prompt(question);
    var key = question.toLowerCase();

    if( answer ) {
        userDetails[key] = answer;
    }
}

I hope this helps, Chris

Thank you Chris!

Really appreciate your help!