es6vue分组某个共同字段_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字段分组,转换成下⾯这种形式:
[
{
"groupname": "值1",
"item": [
{"id": "1", "groupname": "值1", "value": "11"},
{ "id": "2", "groupname": "值1", "value": "22"}
]
vuejson转对象},
{
"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(!upname]){
dest.push({
groupname: ai.groupname,
item: [ai]
});
upname] = ai;
}else{
for(var j = 0; j < dest.length; j++){
var dj = dest[j];
upname== ai.groupname){
dj.item.push(ai);
break;
}
}
}}
console.log(dest);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论