假如有這樣一組數(shù)據(jù)
var oldData=[
{date:'2019-08-26',"queue_id":219,"queue_num":4,"queue_status":1,"queue_name":'預(yù)約接種'},
{date:'2019-08-26',"queue_id":218,"queue_num":2,"queue_status":1,"queue_name":'預(yù)約接種'},
{date:'2019-08-25',"queue_id":217,"queue_num":1,"queue_status":1,"queue_name":'預(yù)約接種'}
]
我想把擁有相同日期的數(shù)據(jù)味廊,放在一個數(shù)組里面渠羞,
第一種方案
1待锈、首先我們把源數(shù)據(jù)先變成目標(biāo)數(shù)據(jù)的規(guī)則
var oldDataRule = []
oldData.forEach(el => {
var oldObj = {
date: el.date,
list:[]
}
oldObj.list.push(el)
oldDataRule.push(oldObj)
})
console.log(oldDataRule)
打印出來的數(shù)據(jù)如下
2、然后我們把源數(shù)據(jù)去重屑迂,把相同日期的數(shù)據(jù)合并成list
var newData = []
var newObj = {}
oldDataRule.forEach((el, i) => {
if (!newObj[el.date]) {
newData.push(el);
newObj[el.date] = true;
} else {
newData.forEach(el => {
if (el.date === oldDataRule[i].date) {
el.list = el.list.concat(oldDataRule[i].list);
// el.list = [...el.list, ...oldDataRule[i].list]; // es6語法
}
})
}
})
console.log(newData)
最后出來的結(jié)構(gòu)如下
第二種方案
var oldDataRule = []
var newData = []
oldData.forEach( item =>{
oldDataRule [item.date] = oldDataRule [item.date] || [];
oldDataRule [item.date].push(item);
})
for (let key in oldDataRule ) {
let obj = {}
obj.date = key
obj.list =arr[key]
newData.push(obj)
}