作者:coderYYY
个人简介:前端程序媛,目前主攻web前端,后端辅助,其他技术知识也会偶尔分享欢迎和我一起交流!(评论和私信一般会回!!)
个人专栏推荐:《前端项目教程以及代码》
在开发中,这种需求还是挺常见的,常用于处理后端返回的数据,话不多说直接上代码:
以下示例是根据性别gender进行分类,要按哪个属性分类就直接把gender替换掉就好
const arr = [
{ name: '李大', age: 20, gender: '男' },
{ name: '张三', age: 25, gender: '女' },
{ name: '王五', age: 20, gender: '女' },
{ name: '赵六', age: 30, gender: '男' },
{ name: '杨二', age: 25, gender: '男' }
];
let tempArr = [];// 分类属性项
var newArr = [];
arr.forEach((i, index) => {
if (tempArr.indexOf(i.gender) === -1) {
newArr.push({
gender: i.gender,
list: [i]
});
tempArr.push(i.gender);
} else {
newArr[tempArr.indexOf(i.gender)].list.push(i)
}
});
console.log(newArr);
[
{
"gender": "男",
"list": [
{
"name": "李大",
"age": 20,
"gender": "男"
},
{
"name": "赵六",
"age": 30,
"gender": "男"
},
{
"name": "杨二",
"age": 25,
"gender": "男"
}
]
},
{
"gender": "女",
"list": [
{
"name": "张三",
"age": 25,
"gender": "女"
},
{
"name": "王五",
"age": 20,
"gender": "女"
}
]
}
]