【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 @   智者见智  阅读(616)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2019-08-02 【JavaScript】关于eval("("+result+")")的认识
点击右上角即可分享
微信分享提示