JavaScript数组通过某个字段进行分组

如下有一组数据,如何根据type字段进行分组

COPY
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[{
"name": "Lete乐特",
"avatar": "https://www.lete114.top/img/avatar.png",
"link": "https://www.lete114.top",
"type": "小白"
}, {
"name": "Lete乐特个人博客",
"avatar": "https://www.lete114.top/img/avatar.png",
"link": "https://blog.lete114.top",
"type": "大佬"
}, {
"name": "Lete乐特导航网",
"avatar": "https://www.lete114.top/img/avatar.png",
"link": "https://webstack.lete114.top",
"type": "大佬"
}, {
"name": "Lete乐特玩音乐",
"avatar": "https://www.lete114.top/img/avatar.png",
"link": "https://music.lete114.top",
"type": "大佬"
}]
COPY
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// 数据
var data = [{
"name": "Lete乐特",
"avatar": "https://www.lete114.top/img/avatar.png",
"link": "https://www.lete114.top",
"type": "小白"
}, {
"name": "Lete乐特个人博客",
"avatar": "https://www.lete114.top/img/avatar.png",
"link": "https://blog.lete114.top",
"type": "大佬"
}, {
"name": "Lete乐特导航网",
"avatar": "https://www.lete114.top/img/avatar.png",
"link": "https://webstack.lete114.top",
"type": "大佬"
}, {
"name": "Lete乐特玩音乐",
"avatar": "https://www.lete114.top/img/avatar.png",
"link": "https://music.lete114.top",
"type": "大佬"
}]

// 分组
function groups(data){
let map = {}
let result = []

// dataIndex.type == 数据的type字段
for (let i in data) {
let dataIndex = data[i]
if (!map[dataIndex.type]) {
map[dataIndex.type] = [dataIndex]
} else {
map[dataIndex.type].push(dataIndex)
}
}

Object.keys(map).forEach(key => {
result.push({
group: key,
data: map[key],
})
})
return result
}
console.log(groups(data));
Authorship: Lete乐特
Article Link: https://blog.imlete.cn/article/JavaScript-array-group.html
Copyright: All posts on this blog are licensed under the CC BY-NC-SA 4.0 license unless otherwise stated. Please cite Lete乐特 's Blog !