有这么一串json数据:
{ "list": [ { "time": "2014", "html": "<div>2014a</div>" }, { "time": "2011", "html": "<div>2011</div>" }, { "time": "2013", "html": "<div>aaa</div>" }, { "time": "2014", "html": "<div>2014b</div>" } ] }
我想,根据时间来拼接成html,同一年度的集合在一个<div class="year"></div>里面,并按照年度从近到远进行排列。用JS如何解析出来?
表达清楚点呀
其实我想得到
<div class="year"> <h3>2014</h3> <div>2014a</div> <div>2014b</div> </div> <div class="year"> <h3>2013</h3> <div>aaa</div> </div> <div class="year"> <h3>2011</h3> <div>2011</div> </div>
@HasBug:
var data = { "list": [ { "time": "2014", "html": "<div>2014a</div>" }, { "time": "2011", "html": "<div>2011</div>" }, { "time": "2013", "html": "<div>aaa</div>" }, { "time": "2014", "html": "<div>2014b</div>" } ] }; var list = data.list; var year = []; list.sort(function (a, b) { return b.time - a.time }); for (i = 0; i < list.length; i++) { if (year.indexOf(list[i].time) < 0) { year.push(list[i].time); } } var html = ''; for (i = 0; i < year.length; i++) { var yearhtml = '<div class="year"><h3>' + year[i] + '</h3>'; for (j = 0; j < list.length; j++) { if (list[j].time == year[i]) { yearhtml += list[j].html; } } yearhtml += '</div>'; html += yearhtml; } console.log(html);
简单点可以这么做,当然算法没有优化什么的,只是把你要的功能实现了
@MrNice: 谢谢,简单易用
创个集合,把标题的键值放进去,然后从list中取出一个个值对比?
1 Array.prototype.distinct = function () { 2 var callback = arguments[0] || function (n) { return n; }; 3 var arr = []; 4 var resultArr = []; 5 for (var i = 0, len = this.length; i < len; i++) { 6 var resultItem = callback(this[i]); 7 if (!~resultArr.indexOf(resultItem)) { 8 resultArr.push(resultItem); 9 arr.push(this[i]); 10 } 11 } 12 return arr; 13 }; 14 Array.prototype.filter = Array.prototype.filter || function () { 15 var callback = arguments[0] || function () { return true; }; 16 var arr = []; 17 for (var i = 0, len = this.length; i < len; i++) { 18 callback(this[i], i) && arr.push(this[i]); 19 } 20 return arr; 21 }; 22 Array.prototype.groupBy = function () { 23 var callback = arguments[0] || function (n) { return n; }; 24 var result = []; 25 var keys = this.map(callback).distinct(); //所有的key 26 for (var i = 0, len = keys.length; i < len; i++) { 27 var k = keys[i]; 28 var arr = this.filter(function (ele) { 29 return callback(ele) == k; 30 }); 31 result.push({ key: k, values: arr }); 32 } 33 return result; 34 };
//这是一个groupBy方法的实现,得到: List<KeyValuePair<T,List<R>>>
试试这么使用:
obj.list.groupBy(function(n){
return n.time;
});
@上位者的怜悯: 好有心,非常感谢!
@上位者的怜悯: 只能选一个最佳,选了楼上的朋友,解决问题,嘿嘿。谢谢
@HasBug: 是的,楼上解决了具体问题。
如果是C#,直接反序列化为一个List,然后Group By+String Builder就实现你的功能了。