Within javascript, I am trying to print the values from a few objects listed in an array in an object. The question has to do with drilling into objects/arrays with a for in loop. More specifically I'd like to avoid using a for loop if possible (I just learned for/in and am trying to understand it well)
The object looks like this:
var users = {
'Students': [
{ first_name: 'Michael', last_name : 'Jordan' },
{ first_name : 'John', last_name : 'Rosales' },
{ first_name : 'Mark', last_name : 'Guillen' },
{ first_name : 'KB', last_name : 'Tonel' }
],
'Instructors': [
{ first_name : 'Michael', last_name : 'Jackson' },
{ first_name : 'Martin', last_name : 'Puryear' }
]
};
How could i write a function that returns all of the names burried in this object? Id like to console log:
Students
1 - MICHAEL JORDAN
2 - JOHN ROSALES
3 - MARK GUILLEN
4 - KB TONEL
Instructors
1 - MICHAEL JACKSON
2 - MARTIN PURYEAR
Ive tried writing a couple for/in loops but I keep getting unexpected results. Thanks in advance for taking a look at this.
You can break a problem like this into smaller parts. First, how to we get at the individual elements of your map?
logs:
So now we can get at the members of
users
one at a time, inside that loop:That extracts an array each time. Now you can loop through the array, by adding this inside the loop we already have:
That prints out individual items from your list, e.g.
{first_name: 'Michael', last_name : 'Jordan'}
Now you can print it in a different way.
Put all these pieces together and you are very close to your goal (You just need to uppercase -- Google it!)
So we have everything we need to achieve in Javascript, what this pseudocode sums up:
You can make this tidier by extracting the inner loop into a function of its own. You can do it in more advanced ways by using functional programming constructs like
array.map()
to translate one array into another. But the pieces above are good "beginners' way" to tackle the problem.