1

OK, so I have a list of objects (with unknown keys), like this :

{"Subtype":
    {"gender":"m"},
    {"number":"pl"}
}

Is there any way I could iterate over the array and also get the different "key" values :

{{#Subtype}}
    {{#.}}
          <li>{{.}}</li>
    {{/.}}
{{/Subtype}}

This just prints out [object Object].

Any ideas?

Dr.Kameleon
  • 21,495
  • 19
  • 103
  • 208

2 Answers2

1

I have done something via JavaScript and implemented in Mustache.

Note: Code is not pure Mustache

JS Code

var mustacheFormattedData = {
    'value': []
};

for (var row in tableRows) {
    if (tableRows.hasOwnProperty(row)) {
        var obj = tableRows[row]
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                console.log(prop)
                mustacheFormattedData['value'].push({
                    'value': obj[prop]
                });
            }
        }
    }
}

JSFiddle

If the person key exists and is not null, undefined, or false, and is not an empty list the block will be rendered one or more times.

When the value is a list, the block is rendered once for each item in the list. The context of the block is set to the current item in the list for each iteration. In this way we can loop over collections.

View:

{
  "stooges": [
    { "name": "Moe" },
    { "name": "Larry" },
    { "name": "Curly" }
  ]
}

Template:

{{#stooges}}
<b>{{name}}</b>
{{/stooges}}

Refer this

Okky
  • 9,370
  • 10
  • 69
  • 116
  • OK, my point is : what if *I don't know* there is an entry with the field `name`? How would I be able to have it echo "Moe","Larry","Curly"? – Dr.Kameleon Jun 13 '14 at 10:15
1

Try this:

var data ={"Subtype":[
    {"gender":"m"},
    {"number":"pl"}]
};
$.each(data, function(key, val) {
    console.log('key');
    console.log(key);
    console.log('val');
    console.log(val);
  $.each(this, function(k, v) {
    /// do stuff
      console.log('k = '+k+ ' v = '+v)
      console.log(v)
      $.each(this, function(k1, v1) {
          console.log('k1 = '+k1+ ' v1 = '+v1)
      })    
  });
});
Rahul Gupta
  • 7,933
  • 5
  • 49
  • 60