<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JS</title>
</head>
<body>
<script>
var data = [
{
date: "汉语",
count: 1,
},
{
date: "日语",
count: 2,
},
{
date: "汉语",
count: 3,
},
{
date: "日语",
count: 7,
},
{
date: "法语",
count: 5,
},
];
var dataContainer = {}; //存分组的
data.map((item) => {
//对数据进行遍历
//dataContainer['汉语'] (给dataContainer对象添加了一个'汉语'键名) = dataContainer['汉语'] (第一次循环dataContainer['汉语'] 没有值,所以为undefined) || []
dataContainer[item.date] = dataContainer[item.date] || [];
dataContainer[item.date].push(item);
});
console.log(dataContainer);
var total = []; //最后统计结束的数据
var dataName = Object.keys(dataContainer); // 获取分组的键名:["汉语", "法语"] Object.keys:可以将对象的键名存到一个数组中去
console.log(dataName)
dataName.map((nameItem) => {
//循环键名
let count = 0; //每个分组的count 都会在外层循环清0
dataContainer[nameItem].map((item) => {
count = item.count + count; // 遍历每个种类,每循环一次,该分组的count 就 +1
});
//内层循环结束后,在外层最后,将你需要的数据,存到一个对象中去即可
total.push({ name: nameItem, total: count });
});
console.log(total);
</script>
</body>
</html>