按照“谁”分组,就让这个“谁”作为结果对象的 key,然后把匹配的数据分别放在这些 key 对应的 value 下面
<html>
<head>
<title>对数据分组处理</title>
</head>
<body>
</body>
<script>
const data = [
{
name: 'zhangsan',
gender: 'male',
age: 18
},
{
name: 'lisi',
gender: 'male',
age: 20
},
{
name: 'wangwu',
gender: 'female',
age: 19
},
{
name: 'zhaoliu',
gender: 'female',
age: 9
},
{
name: 'hahh',
gender: 'male',
age: 20
},
{
name: 'heihei',
gender: 'female',
age: 19
},
]
function handleDepartData(data, key) {
let obj = {}
data.forEach(item => {
let value = item[key]
obj[value] = obj[value] || []
obj[value].push(item)
})
return obj
}
const dataHandled = handleDepartData(data, 'age')
console.log(dataHandled)
</script>
</html>
按照 age 分组
按照 gender 分组
标签:obj,name,处理,gender,age,value,JS,分组 From: https://www.cnblogs.com/zjy4fun/p/17683443.html