0

我有一个 json 字符串。看起来像:

  var data= [{"name":"Name1","value":"Value1","group":"Group1","order":"1"},
      {"name":"Name2","value":"Value2","group":"Group1","order":"2"},
      {"name":"Name3","value":"Value3","group":"Group1","order":"3"},
      {"name":"Name4","value":"Value4","group":"Group2","order":"4"},
      {"name":"Name5","value":"Value5","group":"Group2","order":"5"},
      {"name":"Name6","value":"Value6","group":"Group3","order":"6"},
      {"name":"Name7","value":"Value7","group":"Group4","order":"7"},
      {"name":"Name8","value":"Value8","group":"Group4","order":"8"},
      {"name":"Name9","value":"Value9","group":"Group4","order":"9"}]

是否可以使用 mootools javascript 库将其转换为 html 输出并按顺序排序:

 <h2>Group1</h2> 
 <div>Name1 ... Value1</div>
 <div>Name2 ... Value2</div>
 <div>Name3 ... Value3</div>
 <h2>Group2</h2> 
 <div>Name4 ... Value4</div>
 <div>Name5 ... Value5</div>
 <h2>Group3</h2> 
 <div>Name6 ... Value6</div>
 <h2>Group4</h2> 
 <div>Name7 ... Value7</div>
 <div>Name8 ... Value8</div>
 <div>Name9 ... Value9</div>

这是我的排序功能:

data.sort(function(a,b){
   return parseInt(a.order) > parseInt(b.order);
});

我的渲染功能如下:

var html_data = '';
data.each(function(d){      
       html_data += tmpl.render("data", d);            
}); 

container.set('html', html_data);

但我不知道如何分组。

谢谢!

4

1 回答 1

1

只需在每个循环中测试组中的先前值:

var html_data = '';
var group = '';
data.each( function( item, index ) {
    if ( group !== item.group ) {
        html_data += '<h2>'+item.group+'</h2>';
    }
    html_data += '<div>'+item.name+'...'+item.value+'</div>';
    group = item.group;
});

container.set( 'html', html_data );
于 2013-05-21T13:12:43.147 回答