0

Help! This should't be so difficult, so I assume I'm missing something easy...

I have a variable that's serving as an underscore template. Here's an example (there's more to it, but for simplicity's sake, this is the code that matters):

var template = '<% _.each(favorites, function(value, key) { %> <li><%= key %>: <%= value %></li> <% }); %>';

And what's in 'favorites' you might ask? It's coming from a JSON object that looks something like this (cutting out the other JSON).

"favorites" : [
    { "food" : "shrimp" },
    { "drink" : "none" }
]

Why on earth can I not figure out how to get the key/value pairs to output in the template. All I want to do is print something like this:

<li>food: shrimp</li>
<li>drink: none</li>

What am I doing wrong?

1
  • 1
    What you have is a collection not an object. You have to loop the array and access the keys with dot notation. But your data structure isn't quite right... Commented Feb 26, 2014 at 6:43

1 Answer 1

1

I'd start with a different data structure, a proper collection:

favorites: [
  {type: "food", name: "shrimp"},
  {type: "drink" name: "none"}
];

Then you can create your template like:

var template = [
  '<% _.each(favorites, function(item) { %>',
    '<li><%= item.type %>: <%= item.name %></li>',
  '<% }); %>'
].join('');
Sign up to request clarification or add additional context in comments.

1 Comment

That totally works. Thank you, thank you, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.