0

Goal: Dynamically populate an inline ul with images depending on values inside an array. If the array has a value that corresponds to an image then the appropriate image will be displayed.

My array will have values like "Organic", "Paleo", "Vegan", "Soy Free", and other descriptions that refer to food.

For my code the name of the array I'll be referencing will be state.greens[0] (or more generically state.greens[n].features), and because of my existing code it'd be easier to pass in state.greens[0] as an argument instead of state.greens[0].features, so I'd prefer to do it this way if possible.

My code:

var icons = function(array) {
    var pics = {
        Organic: "http://www.healthkismet.com/img/picker/icon.png",
        Vegan: "http://www.healthkismet.com/img/picker/vegan.png",
        Paleo: "http://www.healthkismet.com/img/picker/paleo.png"
    }

    for (var i = 0; i < array.features.length; i++) {
        $(".info ul").append("<li><img src=" + pics.array.features[i] + "></img></li>");
    }
}

HTML (using twitter bootstrap)

<div class="info">
    <ul class="list-inline">
    </ul>
</div>

The idea here is that if the following is true:

state.greens[0].features = ["Organic", "Paleo"]

Then the ul will populate like so:

<div class="info">
  <ul class="list-inline">
    <li><img src="pics.Organic"></img></li>
    <li><img src="pics.Paleo"></img></li>
  </ul>
</div>

And the images will show up.

Right now I'm getting the following error:

Uncaught TypeError: Cannot read property 'length' of undefined

I assume it's not turning pics.state.greens[0].features[i] into any value.

Any help would be appreciated. Thank you.

Jonathan Bechtel
  • 3,497
  • 4
  • 43
  • 73
  • "... it'd be easier to pass in state.greens[0].features as an argument instead of state.greens[0].features..." both are state.greens[0].features. Can you check your typing? – Kevin Le - Khnle Jun 04 '15 at 19:33
  • If `array` here is `state.greens[0]`, then you simply need to do `pics[array.features[i]]`. However, your error suggests to me that `array` does not have a `features` property. – apsillers Jun 04 '15 at 19:34
  • @Khnle-Kevin - Thank you, I fixed it. I'd prefer to pass in state.greens[0], NOT state.greens[0].features. – Jonathan Bechtel Jun 04 '15 at 19:37
  • @apsillers - I made the edit you suggested and the error message went away, however the pics did not show up. I double checked the URL's for the images, and the html the function was grabbing and they're both correct. Do you know what else it could be? – Jonathan Bechtel Jun 04 '15 at 19:45

0 Answers0