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

js对象数组(JSON) 根据某个共同字段 分组_第1张图片
js对象数组(JSON) 根据某个共同字段 分组_第2张图片
js对象数组(JSON) 根据某个共同字段 分组_第3张图片

希望的是将下面的对象数组:

[

    {"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"}

        ]

    },

    {

        "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);

你可能感兴趣的:(js对象数组(JSON) 根据某个共同字段 分组)