# 求解，json解析并按照年度为一组拼接成html

0

```{
"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>"
}
]
}```

1

MrNice | 老鸟四级 |园豆：3452 | 2015-07-17 15:33
```其实我想得到<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 | 园豆：3452 (老鸟四级) | 2015-07-17 16:31

@MrNice: 谢谢，简单易用

0

1
``` 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: 是的，楼上解决了具体问题。

0

您需要登录以后才能回答，未注册用户请先注册