jquery把数组中年月相同的数组重新组成新的数组


//原数组
var data = {
    results: [{
id:0,
date:'2017-12-12',
content:'123'
},{
id:0,
date:'2017-12-12',
content:'123'
},{
id:0,
date:'2017-11-12',
content:'123'
},{
id:0,
date:'2018-04-12',
content:'123'
}],
totalSize: 46,
validNumber: 0
}

var data2 = {};
var arr = [];
var keyMap = {};
for (var i = 0; i < data.results.length; i++) {
var arrElem = data.results[i];
var elemKey = arrElem.date.substring(0, 7);//截取年月
if (elemKey in keyMap) {
arr[keyMap[elemKey]].value.push(arrElem);
} else {
arr.push({
"date": arrElem.date.substring(0, 7),
"value": [arrElem]
});
keyMap[elemKey] = arr.length - 1;
}
}
data2 = {
results:arr,
totalSize: 46,
validNumber: 0
}
console.log(data2);

//处理后的结果
var data2 = {
results: [{
date:'2017-12',
value:[{
id:0,
date:'2017-12-12',
content:'123'
},{
id:0,
date:'2017-12-12',
content:'123'
}],
},{
date:'2017-11',
value:[{
id:0,
date:'2017-11-12',
content:'123'
}],
},{
date:'2018-04',
value:[{
id:0,
date:'2018-04-12',
content:'123'
}],
}],
totalSize: 46,
validNumber: 0
}
 
 

 

posted @ 2018-04-28 16:36  青青子衿619  阅读(221)  评论(0编辑  收藏  举报