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);
推荐阅读
- 数组常用方法一
- Java|Java基础——数组
- jQuery插件
- iOS面试题--基础
- JS常见数组操作补充
- 口红选得好,对象不愁找......
- java静态代理模式
- Python-类和对象
- JS|JS 数组求和与数组求平均值
- 超帅的js数组去重