请帮助弄清楚如何分组和显示JSON对象。 这是我的榜样:
{{1}}
我想使用jQuery对具有相同id的名称进行分组。 希望你能帮助我解决这个问题。我会非常感谢你。
提前谢谢!
答案 0 :(得分:1)
var result = [
{
"data":
[{
"id": 1,
"name": "aaa"
}]
},
{
"data":
[{
"id": 2,
"name": "bbb"
}]
},
{
"data":
[{
"id": 1,
"name": "cccc"
}]
},
{
"data": [{
"id": 3,
"name": "ddd"
}]
},
{
"data": [{
"id": 2,
"name": "eee"
}]
},
{
"data":
[{
"id": 3,
"name": "fff"
}]
}
];
var groups={};
$.each(result,function(key,val){
$.each(val.data,function(k,v){
var id = v.id;
if(groups[id]){
groups[id]['name'].push(v.name);
}else{
groups[id] = {};
groups[id]['name'] = [];
groups[id]['name'].push(v.name);
groups[id]['id'] = v.id;
}
});
});
console.log(groups);
jsfiddle:http://jsfiddle.net/jm3kr12w/1/
答案 1 :(得分:0)
试试这个。希望对你有用。
var groups = {};
$.each(result,function(key,val){
var data=val.data;
$.each(data,function(k,v){
var id = v.id;
if(groups[id]){
groups[id].push(v);
}else{
groups[id] = [];
groups[id].push(v);
}
});
});
console.log(groups);
输出
{
"1": [
{
"id": 1,
"name": "aaa"
},
{
"id": 1,
"name": "cccc"
}
],
"2": [
{
"id": 2,
"name": "bbb"
},
{
"id": 2,
"name": "eee"
}
],
"3": [
{
"id": 3,
"name": "ddd"
},
{
"id": 3,
"name": "fff"
}
]
}
答案 2 :(得分:0)
试试这个
var result = [
{
"data":
[{
"id": 1,
"name": "aaa"
}]
},
{
"data":
[{
"id": 2,
"name": "bbb"
}]
},
{
"data":
[{
"id": 1,
"name": "cccc"
}]
},
{
"data": [{
"id": 3,
"name": "ddd"
}]
},
{
"data": [{
"id": 2,
"name": "eee"
}]
},
{
"data":
[{
"id": 3,
"name": "fff"
}]
}
]
var tempArray = []
for(var i=0;i<result.length;i++)
{
var o = null;
var index = -1;
for (var j = 0; j <tempArray.length; j++) {
if (stackMethods.tempArray[j].Id == result[i].data[0].id) {
index = j;
o =tempArray[j];
break;
}
}
if(o!=null)
{
o.Names.push(result[i].data[0].name);
tempArray[index] = o;
}
else {
o = {};
o.Id = result[i].data[0].id;
o.Names = [];
o.Names.push(result[i].data[0].name);
tempArray.push(o);
}
}