这里举个例子是根据两个字段分组,多个的话稍微加个判断就能用
例:根据id和groupname进行分类,代码如下
- var arr = [
- { "id": "1", "groupname": "值1", "value": "11" },
- { "id": "1", "groupname": "值1", "value": "12" },
- { "id": "1", "groupname": "值1", "value": "13" },
-
- { "id": "2", "groupname": "值1", "value": "22" },
- { "id": "2", "groupname": "值1", "value": "23" },
- { "id": "2", "groupname": "值1", "value": "24" },
- { "id": "2", "groupname": "值1", "value": "25" },
-
- { "id": "3", "groupname": "值2", "value": "33" },
-
- { "id": "4", "groupname": "值2", "value": "44" },
- { "id": "4", "groupname": "值2", "value": "45" },
-
- { "id": "5", "groupname": "值3", "value": "55" },
-
- { "id": "6", "groupname": "值3", "value": "66" }
- ];
-
- var map = [
- {
- id: arr[0].id,
- groupname: arr[0].groupname,
- item: [arr[0]],
- }
- ]
- for (var i = 1; i < arr.length; i++) {
- let bool = map.some((it)=>{
- if((arr[i].id == it.id) && (arr[i].groupname == it.groupname)){
- it['item'].push(arr[i])
- }
- return ((arr[i].id == it.id) && (arr[i].groupname == it.groupname))
- })
- if(!bool){
- map.push({
- id: arr[i].id,
- groupname: arr[i].groupname,
- item: [arr[i]],
- })
- }
- }
- console.log(map);
结果如下