# 例子
如果获取到的数据格式是如下的
var arr = [
{"id":"1001","name":"值1","value":"111"},
{"id":"1002","name":"值2","value":"222"},
{"id":"1002","name":"值2","value":"333"},
{"id":"1003","name":"值3","value":"444"},
{"id":"1003","name":"值3","value":"555"},
{"id":"1003","name":"值3","value":"666"}
];
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
需要进行如下处理
var map = {},
dest = [];
for(var i = 0; i < arr.length; i++){
var ai = arr[i];
//根据id属性来分组
//如果id属性的值不存在则在对象中创建id属性
if(!map[ai.id]){
dest.push({
id: ai.id,
name: ai.name,
data: [ai]
});
map[ai.id] = ai;
}else{
for(var j = 0; j < dest.length; j++){
var dj = dest[j];
//否则遍历出相同的id并且把值push进去
if(dj.id == ai.id){
dj.data.push(ai);
break;
}
}
}
}
console.log(dest);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
打印的结果为
根据id来分组,将id值相同的分到同一个组里
亲测有效,奔走相告。