【JavaScript】数组通过某个字段进行分组

利用for in 把过滤字段当做属性,通过属性去添加到对象里面,最后把对象通过for in 处理为自己需要的结构

<script type="text/javascript"> 
groupArr: function (list, field) {
    var obj = {};
    for (var i = 0; i < list.length; i++) {
        for (item in list[i]) {
            if (item == field) {
                obj[list[i][item]] = {
                    list: obj[list[i][field]] ? obj[list[i][field]].list : [],
                    type: list[i].type
                };
            }
        }
        obj[list[i][field]].list.push(list[i])
    }
    var att = [];
    for (item in obj) {
        att.push({
            list: obj[item].list,
            type: obj[item].type,
        })
    }
    return att;
},
TestDemo: function (LogisticsNumber, ConsigneeNumber) {
    var list = [{
        id: 0,
        name: "剑圣-刺客",
        type: "刺客"
    },
    {
        id: 1,
        name: "安妮-法师",
        type: "法师"
    },
    {
        id: 3,
        name: "赵信-战士",
        type: "战士"
    },
    {
        id: 4,
        name: "寒冰-射手",
        type: "射手"
    },
    {
        id: 4,
        name: "维恩-射手",
        type: "射手"
    },
    {
        id: 2,
        name: "蕾欧娜-坦克",
        type: "坦克"
    },
    {
        id: 1,
        name: "拉克丝-法师",
        type: "法师"
    },
    {
        id: 0,
        name: "劫-刺客",
        type: "刺客"
    },
    {
        id: 1,
        name: "凤凰-法师",
        type: "法师"
    },
    {
        id: 3,
        name: "皇子-战士",
        type: "战士"
    },
    {
        id: 2,
        name: "龙龟-坦克",
        type: "坦克"
    }]
    var that = this;
    console.log(that.groupArr(list, 'id'))
},
</script>

分组后结果:

原文链接:https://www.jianshu.com/p/b3cef639dc09?open_source=weibo_search 

posted @ 2021-08-02 20:42  智者见智  阅读(605)  评论(0编辑  收藏  举报