js数组对象的合并

在项目中涉及到了数组中对象的合并,在此做个笔记以免忘记

原数组:

[
{name:'测试1',number:'1234',type:'语文'},
{name:'测试1',number:'1424',type:'数学'},
{name:'测试1',number:'543',type:'英语'},
{name:'测试2',number:'765',type:'语文'},
{name:'测试2',number:'3456',type:'数学'},
{name:'测试3',number:'7653',type:'英语'},
]

转换后的数组:

[
    {name:'测试1',number:'1234',type:'语文',array:[
        {name:'测试1',number:'1234',type:'语文'},
        {name:'测试1',number:'1424',type:'数学'},
        {name:'测试1',number:'543',type:'英语'},
    ]},
    {name:'测试2',number:'342',type:'语文',array:[
        {name:'测试2',number:'342',type:'语文'},
        {name:'测试2',number:'4324',type:'数学'},
        {name:'测试2',number:'5543',type:'英语'},
    ]},
]  

使用方式:

let arrWarp = [],result = []; // 定义新的数组
                    for (let item of data) { // 遍历数组
                        if (!arrWarp.includes(item.name)) { // 判断根据哪个参数
                            let obj = {
                                name: item.name,
                                number: item.number,
                                array: []
                            }
                            obj.array.push(item);
                            result.push(obj);
                            arrWarp.push(item.name);
                        } else {
                            result[arrWarp.indexOf(item.name)].array.push(item);
                        };
                    };

 

posted @ 2022-09-27 11:06  zhumeng_WEB  阅读(1717)  评论(0编辑  收藏  举报