js对象数组(JSON)|js对象数组(JSON) 根据某个共同字段 分组

js对象数组(JSON)|js对象数组(JSON) 根据某个共同字段 分组
文章图片
js对象数组(JSON)|js对象数组(JSON) 根据某个共同字段 分组
文章图片
js对象数组(JSON)|js对象数组(JSON) 根据某个共同字段 分组
文章图片
希望的是将下面的对象数组:
[
{"id":"1","groupname":"值1","value":"11"},
{"id":"2","groupname":"值1","value":"22"},
{"id":"3","groupname":"值2","value":"33"},
{"id":"4","groupname":"值2","value":"44"},
{"id":"5","groupname":"值3","value":"55"},
{"id":"6","groupname":"值3","value":"66"}
]
根据相同groupname字段分组,转换成下面这种形式:
[

{
【js对象数组(JSON)|js对象数组(JSON) 根据某个共同字段 分组】"groupname": "值1",
"item": [
{"id": "1", "groupname": "值1", "value": "11"},
{ "id": "2", "groupname": "值1", "value": "22"}
]
},
{
"groupname": "值2",
"item": [
{"id": "3", "groupname": "值2", "value": "33"},
{ "id": "4", "groupname": "值2", "value": "44"}
]
},
{
"groupname": "值3",
"item": [
{"id": "5", "groupname": "值3", "value": "55"},
{ "id": "6", "groupname": "值3", "value": "66"}
]
}
]
做法:
var arr = [ {"id":"1","groupname":"值1","value":"11"},
{"id":"2","groupname":"值1","value":"22"},
{"id":"3","groupname":"值2","value":"33"},
{"id":"4","groupname":"值2","value":"44"},
{"id":"5","groupname":"值3","value":"55"},
{"id":"6","groupname":"值3","value":"66"}
];
var map = {},
dest = [];
for(var i = 0; i < data.length; i++){
var ai = arr[i];
if(!map[ai.groupname]){
dest.push({
groupname: ai.groupname,
item: [ai]
});
map[ai.groupname] = ai;
}else{
for(var j = 0; j < dest.length; j++){
var dj = dest[j];
if(dj.groupname== ai.groupname){
dj.item.push(ai);
break;
}
}
}}
console.log(dest);

    推荐阅读