Array of objects (JSON) grouped by a common field

1. Use js to process the front-end page

Reprint https://www.cnblogs.com/rysinal/p/5834446.html

In order to compare the second method, id is specially converted to pid

var arr = [
    {"pid":"1001","name":"值1","value":"111"},
    {"pid":"1001","name":"值1","value":"11111"},
    {"pid":"1002","name":"值2","value":"25462"},
    {"pid":"1002","name":"值2","value":"23131"},
    {"pid":"1002","name":"值2","value":"2315432"},
    {"pid":"1003","name":"值3","value":"333333"}
];

var map = },
    dest = [];
for(var i = 0; i < arr.length; i++){
    var ai = arr[i];
    if(!map[ai.pid]){
        dest.push (ush
            pid: ai.pid,
            name: ai.name,
            date: [ai]
        });
        map [ai.pid] = ai;
    }else{
        for(var j = 0; j < dest.length; j++){
            var dj = dest[j];
            if(dj.pid == ai.pid){
                dj.data.push(ai);
                break;
            }
        }
    }
}

console.log (dest);

The second, processing in the background (framework tp5)

 foreach($res as $key=>$v)
        {
            $list[$v['pid']][] = $v;
        }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325971779&siteId=291194637