Can I do a jquery-tmpl each over object properties
Asked Answered
T

2

11

The template {{each}} directive works great for iterating over an array like this:

var myArray = ["a","b","c"];

I'm wondering if there is an equivalent for iterating over object properties, i.e.:

var myObj = {"propOne": "a", "propTwo": "b", "propThree": "c"};

I'd like a template that would let me output as

<ul>
  <li><span>propOne</span><span>a</span></li>
  .... etc

For bonus points I'd like to use this template from KnockoutJS.

Timekeeper answered 9/8, 2011 at 1:47 Comment(0)
M
12

Actually {{each}} will walk through properties on an object. You can do something like this:

{{each(prop, val) myObj}}
      <li><span>${prop}</span> - <span>${val}</span></li>
{{/each}}

Here is a sample in Knockout: http://jsfiddle.net/rniemeyer/rpMsM/

If you really want to use the foreach option of the template binding, then the only real option is to map the object to an array of objects with key/value properties. Something like this: http://jsfiddle.net/rniemeyer/rpMsM/1/

Mader answered 9/8, 2011 at 2:1 Comment(1)
Giddy up, that is the bomb! =)Timekeeper
S
8

You can also use this

{{each myObj}}
      <li><span>${$index}</span> - <span>${$value}</span></li>
{{/each}}
Solitaire answered 4/5, 2012 at 9:34 Comment(1)
Need remove one symbol in a variable "$" . From ${$index} to ${index} It's helped for me.Midrib

© 2022 - 2024 — McMap. All rights reserved.