2020年12月21日星期一

How can I divide grouped array-object by length?

I have the following data retrieved from a database

var members = [    { "name" : "a", "department_id" : 1, "department_name" : "aaa" },    { "name" : "b", "department_id" : 1, "department_name" : "aaa" },    { "name" : "c", "department_id" : 1, "department_name" : "aaa" },    { "name" : "d", "department_id" : 1, "department_name" : "aaa" },    { "name" : "e", "department_id" : 1, "department_name" : "aaa" },    { "name" : "f", "department_id" : 2, "department_name" : "bbb" },    { "name" : "g", "department_id" : 2, "department_name" : "bbb" }  ];  

The first step is to group this data by department name.

var groupedMembers = _.groupBy(members, "department_name");    ↓    {    "aaa" : [      { "name" : "a", "department_id" : 1, "department_name" : "aaa" },      { "name" : "b", "department_id" : 1, "department_name" : "aaa" },      { "name" : "c", "department_id" : 1, "department_name" : "aaa" },      { "name" : "d", "department_id" : 1, "department_name" : "aaa" },      { "name" : "e", "department_id" : 1, "department_name" : "aaa" }    ],    "bbb" : [      { "name" : "f", "department_id" : 2, "department_name" : "bbb" },      { "name" : "g", "department_id" : 2, "department_name" : "bbb" }    ]  }  

From this state, I want to further split the object into every three objects.

Ideally, I would like the array to be formatted in the following way

var expected = {    "aaa1" : [      { "name" : "a", "department_id" : 1, "department_name" : "aaa" },      { "name" : "b", "department_id" : 1, "department_name" : "aaa" },      { "name" : "c", "department_id" : 1, "department_name" : "aaa" }    ],    "aaa2" : [      { "name" : "d", "department_id" : 1, "department_name" : "aaa" },      { "name" : "e", "department_id" : 1, "department_name" : "aaa" }    ],    "bbb" : [      { "name" : "f", "department_id" : 2, "department_name" : "bbb" },      { "name" : "g", "department_id" : 2, "department_name" : "bbb" }    ]  };  

Can I solve that by using Underscore.js or lodash.js? If it's not too difficult, you can use other libraries or pure javascript implementations.

Thank you.

https://stackoverflow.com/questions/65402630/how-can-i-divide-grouped-array-object-by-length December 22, 2020 at 10:45AM

没有评论:

发表评论