使用map数据结构的,键值唯一性进行操作
//根据年龄分组,获取目标数据格式
//[{key:key,data:[{}]}]
//{key:[]}
const arr = [
{ name:'test1',age:10},
{ name:'test2',age:20},
{ name:'test3',age:10},
{ name:'test4',age:20},
{ name:'test5',age:10},
{ name:'test6',age:20},
]
let map = new Map()
arr.map(it=>{
map.set(it.age,[...map.get(it.age)||'',it])
})
let objs = Object.fromEntries(map.entries())
let toArr=[]
for(let [key,value] of map){
toArr.push({
key:key,
data:value
})
}
console.log(toArr,111)
console.log(objs,222)
效果: