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

Loop through js object (e.g. points) like an array

Hi there,

What we do, we let our code return the points for a specific language (e.g. profile.points.JavaScript). And it works well.

In case we have a long list and we want to sum up to a total, what is the easiest way to do it?

Can we just save the object to an array and then loop through it? Or is there a proper way to do it? I found some infos with jQuery, but couldn't make it work. Then I tried this:

var arr = Object.keys(points).map(function (key) { console.log (points[key]); });

It works ok. But an array would be easier...

Thanks :) Jo

regards this course: https://teamtreehouse.com/library/capturing-command-line-arguments

2 Answers

Steven Parker
Steven Parker
243,318 Points

The result of calling Object.keys is an array. That's why you are able to use "map" (which is an array method) on it.

Hi Steven, Thanks! true. I can use "keys()" to get an array. The second step would be to loop through. something like this:

var array = Object.keys(points) //returns the languages e.g. swift, JavaScript,.. for (var i =0, i<array.length, i += 1){ https://teamtree.......json/usename.${array[i]}; ....

I think it should work.

Thanks. Jo

Steven Parker
Steven Parker
243,318 Points

Sure, you could use a loop to do that. But this might be a good time to use "reduce". (And I don't understand why part of the code snippet looks like a URL)