初始数据
var list = [
{
"id": 1,
"modes": "CHARTBAR_1",
},
{
"id": 2,
"modes": "CHARTBAR_1",
},
{
"id": 3,
"modes": "CHARTBAR_2",
},
{
"id": 4,
"modes": "CHARTBAR_2",
},
{
"id": 5,
"modes": "CHARTBAR_3",
},
{
"id": 6,
"modes": "CHARTBAR_4",
},
{
"id": 7,
"modes": "CHARTBAR_4",
},
{
"id": 8,
"modes": "CHARTBAR_1",
},
{
"id": 9,
"modes": "CHARTBAR_1",
},
{
"id": 10,
"modes": "CHARTBAR_1",
},
]
我需要数据根据modes字段重新组合成新的对象数组,比如整合成下面这样:
[{
"modes": "CHARTBAR_1",
"list": [{
"id": 1,
"modes": "CHARTBAR_1"
}, {
"id": 2,
"modes": "CHARTBAR_1"
}, {
"id": 8,
"modes": "CHARTBAR_1"
}, {
"id": 9,
"modes": "CHARTBAR_1"
}, {
"id": 10,
"modes": "CHARTBAR_1"
}]
}, {
"modes": "CHARTBAR_2",
"list": [{
"id": 3,
"modes": "CHARTBAR_2"
}, {
"id": 4,
"modes": "CHARTBAR_2"
}]
}, {
"modes": "CHARTBAR_3",
"list": [{
"id": 5,
"modes": "CHARTBAR_3"
}]
}, {
"modes": "CHARTBAR_4",
"list": [{
"id": 6,
"modes": "CHARTBAR_4"
}, {
"id": 7,
"modes": "CHARTBAR_4"
}]
}]
方法如下
function getListGroupBy(list, key) {
var keysArr = list.map(item=>item[key])
var keys = [...new Set(keysArr)]
var newList = keys.map(item=> {
return {
[key]: item,
list: list.filter(i=>i[key] == item)
}
})
return newList
}
var newList = getListGroupBy(list, 'modes')
console.log(newList)
可封装为全局方法,使用时直接调用getListGroupBy()函数即可