js 对象数组根据某个属性分组

function arrayGroupBy(list, groupId){
    function groupBy(array, f){
        const groups = {}
        array.forEach(function (o) {
            const group = JSON.stringify(f(o))
            groups[group] = groups[group] || []
            groups[group].push(o)
        })

        return groups;
        // return Object.keys(groups).map(function (group) {
        //     return groups[group]
        // })
    };
    return groupBy(list, function (item) {
        return item[groupId]
    });
};

var response = [ {name:'张三', age:14}, {name:'李四', age:15}, {name:'王五', age:16}, {name:'小明', age:15}, {name:'小云', age:16} ];

var responseObj = arrayGroupBy(response, 'age');

console.log('分组前:',response);
console.log('分组后:',responseObj);
image.png

你可能感兴趣的:(js 对象数组根据某个属性分组)