Question

Ex: Attached Fiddle: http://jsfiddle.net/UNsDK/26/

I have an object called Cards filled with objects containing arrays.I do not know what the index title will be since the object could be different for any user:

 var obj = {'Cards':  {"Pack1":[{"name":"John","color":"red"}],
                       "Pack2":[{"name":"Smith","color":"green"}]}};

In this array Pack1, and Pack2 could have different names, but the inner content is consistent.

Therefore I cannot creature a template like below:

{{#Cards}}
{{#Pack1}}{{name}} {{color}} {{/Pack1}}
{{#Pack2}}{{name}} {{color}} {{/Pack2}}
..
{{/Cards}}

So i'm attempting to do it a different way by mapping the data into a array and and sending that to the template but it's not working: also my view object is losing the indexes of my Cards object.

var len = $.map(obj.Cards, function(n, i) { return i; }).length;
console.log('Length of Cards object is ' + len);
var view = {};
view["Packs"] =$.map(obj.Cards, function(n, pack_name) { 
    console.log('this is:'+pack_name);
    for (var key in n) { 
        var obj = n[key];
        for (var prop in obj) {
            // important check that this is objects own property 
            // not from prototype prop inherited
            if(obj.hasOwnProperty(prop)) {
                console.log(prop + " = " + obj[prop]);
                return prop = obj[prop];
            }
        }
    }           
}); //end map

var template = '<ul> {{#Packs}} <li>{{id}} : {{name}} -- {{color}} </li> {{/Packs}} </ul>';
var html = Mustache.to_html(template, view);
var json = JSON.stringify(view); 
$('#sampleArea').html(html);
Was it helpful?

Solution

You can convert your obj.Cards from map to array of objects containing id and data which was recently obj.Cards[id]. That will allow you to use nested repeaters. In this case your code may be something like that:

JavaScript

function convert(obj) {
  var data = [],
      item,
      id,
      card,
      i;
  for(id in obj.Cards) {
    if(obj.Cards.hasOwnProperty(id)) {
      card = obj.Cards[id];
      item = {
        id: id,
        data: []
      };
      for(i=0; i<card.length; i++) {
        item.data.push( $.extend({},card[i]) );
      }
      data.push(item);
    }
  }
  return {Cards: data};
}

var obj = {
  "Cards":{
    "Pack1":[{
      "name":"John",
      "color":"red"
    }, {
      "name":"Doe",
      "color":"blue"
    }],
    "Pack2":[{
      "name":"Smith",
      "color":"green"
    }]
  }
};

var template = '{{#Cards}}' +
                 '<div>{{id}}</div>' +
                 '<ul>' +
                   '{{#data}}<li>{{name}}: {{color}}</li>{{/data}}' +
                 '</ul>' +
               '{{/Cards}}';

var model = convert(obj);

$('body').append(Mustache.render(template, model));

JSBin: http://jsbin.com/zujiqoyi/1/edit

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top