项目过程中会碰到一些场景需要将有多条数据的对象数组按照对象的某些字段名进行分组,本文使用lodash中的_.groupBy来完成该操作,并对该方法进行初级封装。
以vue2.0脚手架为例
一、安装lodash
在项目内安装
yarn add lodash
//或者
npm i lodash -S
二、引入全部lodash代码
import _ from "lodash";//vue文件内使用
//或者
const _ = require("lodash");//js文件内使用,vue文件内也可用
三、封装函数完成对象数组的按特定字段名分组
//data:数据源,type:分组的依据,value:分组后的key值,datas:分组后的value值,是一个数组
function setData(data, type, value, datas) {
let arr = [];
value = value || "value";
//分组后的key值不传默认为value,分组后的value值不传默认为children
datas = datas || "children";
for (let key in _.groupBy(data, type)) {
arr.push({
[value]: key,
[datas]: _.groupBy(data, type)[key],
});
}
return arr;
}
四、实例
有下列数组,将其按照className分组
let arr = [
{ id: 1, className: "ZZ20230101", student: ["张三", "李四"] },
{ id: 2, className: "ZZ20230102", student: ["王五", "赵六"] },
{ id: 3, className: "ZZ20230103", student: ["小明", "李华"] },
{ id: 4, className: "ZZ20230101", student: ["张大伟", "仍未到"] },
{ id: 5, className: "ZZ20230101", student: ["十五", "逸散"] },
{ id: 6, className: "ZZ20230103", student: ["Bob", "刘凯"] },
{ id: 7, className: "ZZ20230102", student: ["大碗饭", "汪汪"] },
{ id: 8, className: "ZZ20230101", student: ["定位三", "布局"] },
{ id: 9, className: "ZZ20230103", student: ["固定", "绝对"] },
{ id: 10, className: "ZZ20230101", student: ["达瓦", "哇哇的"] },
{ id: 11, className: "ZZ20230102", student: ["五五分", "来对待"] },
];
let arr1 = setData(arr, "className","className","datas");
console.log(arr1);
输出结果
//输出结果如下
[
{
className: "ZZ20230101",//className取决于传的第三个参数,默认为value
datas: [//datas取决于第四个参数,默认为children
{
id: 1,
className: "ZZ20230101",
student: ["张三", "李四"],
},
{
id: 4,
className: "ZZ20230101",
student: ["张大伟", "仍未到"],
},
{
id: 5,
className: "ZZ20230101",
student: ["十五", "逸散"],
},
{
id: 8,
className: "ZZ20230101",
student: ["定位三", "布局"],
},
{
id: 10,
className: "ZZ20230101",
student: ["达瓦", "哇哇的"],
},
],
},
{
className: "ZZ20230102",
datas: [
{
id: 2,
className: "ZZ20230102",
student: ["王五", "赵六"],
},
{
id: 7,
className: "ZZ20230102",
student: ["大碗饭", "汪汪"],
},
{
id: 11,
className: "ZZ20230102",
student: ["五五分", "来对待"],
},
],
},
{
className: "ZZ20230103",
datas: [
{
id: 3,
className: "ZZ20230103",
student: ["小明", "李华"],
},
{
id: 6,
className: "ZZ20230103",
student: ["Bob", "刘凯"],
},
{
id: 9,
className: "ZZ20230103",
student: ["固定", "绝对"],
},
],
},
];
五、脚手架内使用
可以将该函数在 main.js 内绑定在Vue原型上,这样可以全局调用
import _ from "lodash";
//data:数据源,type:分组的依据,value:分组后的key值,datas:分组后的value值,是一个数组
function setData(data, type, value, datas) {
let arr = [];
value = value || "value";
//分组后的key值不传默认为value,分组后的value值不传默认为children
datas = datas || "children";
for (let key in _.groupBy(data, type)) {
arr.push({
[value]: key,
[datas]: _.groupBy(data, type)[key],
});
}
return arr;
}
Vue.prototype.$setData = setData;
六、使用方法
this.$setData(arr, "className")