数组对象根据某个值相同合并分组

var arr = [

    {"id":"1001","name":"值1","value":"111"},

    {"id":"1001","name":"值1","value":"11111"},

    {"id":"1002","name":"值2","value":"25462"},

    {"id":"1002","name":"值2","value":"23131"},

    {"id":"1002","name":"值2","value":"2315432"},

    {"id":"1003","name":"值3","value":"333333"}

];

dealUniqueArray('id',arr);

/*propName需要根据某属性名进行合并分组;arr需要进行合并分组的数据源*/
function dealUniqueArray(propName,arr){

        var map = {},

        dest = [];

  for(vari =0;i < arr.length;i++){

        var ai = arr[i];

          if(!map[ai[propName]]){

                var obj={};

                obj[propName]=ai[propName];

                 obj.data=[ai];

                 dest.push(obj);

                 map[ai[propName]] = ai;

              }else{

                    for(varj =0;j < dest.length;j++){

                            var dj = dest[j];

                             if(dj[propName] == ai[propName]){

                                    dj.data.push(ai);

                                      break;

                            }

                    }

            }

    }

    console.log('dest',dest);

      return dest;

}

你可能感兴趣的:(数组对象根据某个值相同合并分组)