需求:

合并数组的相同的key值,并且计算相同key值的个数

场景:

根据list数组的每一项的key值coupon_sn合并数组,并且计数

js代码

json数组:
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
let list = [{
"id": 5899,
"is_use": 0,
"use_time": null,
"expired_time": "2018-12-31 00:00:00",
"coupon": {
"coupon_sn": "1",
"name": "满减",
"type": 2,
"count": 99993,
"receive_count": 6,
"is_fare": 0,
"available_money": "2000.00",
"reduce_money": "100.00",
"discount": "1.000",
"receive_start_time": "2018-07-27 00:00:00",
"receive_end_time": "2020-12-31 00:00:00",
"info": "",
"created_at": "2018-07-27 21:22:51",
"restriction_description": "仅限非板材使用"
}
}, {
"id": 5899,
"is_use": 0,
"use_time": null,
"expired_time": "2018-12-31 00:00:00",
"coupon": {
"coupon_sn": "2",
"name": "满减",
"type": 2,
"count": 99993,
"receive_count": 6,
"is_fare": 0,
"available_money": "2000.00",
"reduce_money": "100.00",
"discount": "1.000",
"receive_start_time": "2018-07-27 00:00:00",
"receive_end_time": "2020-12-31 00:00:00",
"info": "",
"created_at": "2018-07-27 21:22:51",
"restriction_description": "仅限非板材使用"
}
}, {
"id": 5899,
"is_use": 0,
"use_time": null,
"expired_time": "2018-12-31 00:00:00",
"coupon": {
"coupon_sn": "2",
"name": "满减",
"type": 2,
"count": 99993,
"receive_count": 6,
"is_fare": 0,
"available_money": "2000.00",
"reduce_money": "100.00",
"discount": "1.000",
"receive_start_time": "2018-07-27 00:00:00",
"receive_end_time": "2020-12-31 00:00:00",
"info": "",
"created_at": "2018-07-27 21:22:51",
"restriction_description": "仅限非板材使用"
}
}]
js代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 let hash = {
coupon: {},
}, i = 0, res = [];
list.forEach(function(item ) {
let coupon_sn = item.coupon.coupon_sn;
if (hash[coupon_sn]) {
if (!res[hash[coupon_sn] - 1].count) {
res[hash[coupon_sn] - 1].count = 1
}
res[hash[coupon_sn] - 1].count += 1
} else {
hash[coupon_sn] = ++i && res.push({
"count": 1,
"id": item.id,
"is_use": item.is_use,
"use_time": item.use_time,
"expired_time": item.expired_time,
"coupon": item.coupon
})
}
});
console.log(res);

转载请保持原始链接

原始链接: https://ru23.com/note/6de8207f.html