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

Adam Evans
Adam Evans
6,975 Points

How to use the key value of an Object in my jQuery function

Hi Everyone. I got help with this earlier on and am back for some assistance. If you check out my codepen, you can see my calendar page. I am using jQuery to add running data from a JS object into each day of the calendar in the HTML. I am now trying to link the text I am adding to a photo with some GPS data of the run. The photo for the run will be named 'aug1', 'aug2' so the number corresponds with the day of the run and thus with the key value in the object storing the data. How can I access the key and tack it onto the photo name? I can get it to work with a static number added on but I cannot seem to get the key value.

Codepen: http://codepen.io/Alevans/pen/aJDzH

var august = {1: 6,
              5: 3,
              6: 4,
              7: 3,
              9: 7,
           };

var augustKeys = Object.keys(august);

$(document).ready(function() {
$("div.tabs > div.tab > div.august > div ").each(function () {
  if(august.hasOwnProperty($(this).text())) {
    $(this).append('<p><a href="img/aug' + SomeWayToAddKeyValueOfCurrentData + '.png">' + august[$(this).text()] + ' miles</a></p>');
  }
})})

I created the variable augustKeys that stores the values of the keys and I thought accessing that would be easy but I can't seem to get it to work. The final function above is what adds the text (i.e. '6 Miles') to the HTML. I've gotten it to the point where I can link a single photo to all of the runs but I need to add a unique photo to each. The key value and the date at the end of the photo name are the same, so I would think I could do this somehow. All help is appreciated!

Thanks!

1 Answer

Michael Hinrichs
Michael Hinrichs
10,920 Points

I would think you could just do something like august[1].

So that would mean you need some sort of a loop or iterator in your each function, like so:

each(obj, function(i){})

Then you will be able to say something like

+ obj[i] +

when you try to append something.

Check out the jQuery each() if you get lost! http://api.jquery.com/jquery.each/

Hope that helps! :)