let list = [ {name:"1000积分",serialNumber:6}, {name:"500积分",serialNumber:7}, {name:"50积分",serialNumber:8}, {name:"50积分",serialNumber:8}, {name:"50积分",serialNumber:8} ];
怎么把list数组转化为
[
{title:"1000积分",num:1},
{title:"500积分",num:1},
{title:"50积分",num:3}
]
//num:serialNumber相同的元素重复次数
首先要先获取同样的serialNumber的重复次数
//先根据所有的title组合成一个数组
let titleList = list.map(item => {
return item.name
})
//获得["1000积分", "500积分", "50积分", "50积分", "50积分"]
然后有两种方法将titleList 转化
// 不用reduce时: function getRepeatNum(){ var obj = {}; for(var i= 0, l = titleList.length; i< l; i++){ var item = arr[i]; obj[item] = (obj[item] +1 ) || 1; } return obj; } //用reduce时: //reduce:计算数组元素相加后的总和
//reduce方法接受两个参数,第一个是函数,第二个是初始值 function getRepeatNum(){ return titleList.reduce(function(prev,next){ prev[next] = (prev[next] + 1) || 1; return prev; },{}); } console.log(getRepeatNum());//获得{1000积分: 1, 500积分: 1, 50积分: 3}
let myObj = this.getRepeatNum2(titleList),
winningList = []
for(let i in myObj){
let obj = {
title:i,
num:myObj[i]
}
winningList.push(obj)
}
console.log(winningList)
//[{"title":"1000积分","num":1},{"title":"500积分","num":1},{"title":"50积分","num":3}]