js合并多维数组并去重

合并多维数组,网上有挺多例子,可惜都不是我需求的模样,于是自己花了点时间整理了一下出来

思路比较清晰,看到多维,想到的方法便是降维,于是,利用了对象键值对的关系用来做判断

直接上代码了:例子只考虑了两个列表都有数据的情况,其他情况就加一下简单判断就行了

let arr1=[
    {
        name:"测试1",
        list:[
            {
                id:"1",
                content:{}
            },
            {
                id:"2",
                content:{}
            },
            {
                id:"3",
                content:{}
            }
        ]
    },
    {
        name:"测试2",
        list:[
            {
                id:"4",
                content:{}
            },
            {
                id:"5",
                content:{}
            }
        ]
    }
]

let arr2=[
    {
        name:"测试1",
        list:[
            {
                id:"1",
                content:{}
            },
            {
                id:"5",
                content:{}
            }
        ]
    },
    {
        name:"测试4",
        list:[
            {
                id:"6",
                content:{}
            },
            {
                id:"7",
                content:{}
            }
        ]
    }
]

//临时数组,用来存储合并后的内容
let resultList = [];
//隐藏对象,用来判断name是否存在
let cacheObject = {};
//合并两个数组
let newList = arr1.concat(JSON.parse(arr2));
newList.forEach(item => {
    //判断对象中是否存在对应建
    if (!cacheObject[item.name]) {
        //如果不存在,直接push
        cacheObject[item.name] = item.list;
        resultList.push(item);
    } else {
        //如果存在,判断list字段里面是否相同id
        let pos = Object.keys(cacheObject).findIndex(
            key => key === item.name
        );
        //与上面临时数组对象相同(后续有时间可优化为递归遍历)
        let listItems = [];
        let cacheIds = {};
        item.list
            .concat(cacheObject[item.name])
            .forEach(sitem => {
                //判断brandId是否存在
                if (!cacheIds[sitem.brandId]) {
                    cacheIds[sitem.brandId] = sitem;
                    listItems.push(sitem);
                }
            });
        resultList[pos].list = listItems;
    }
});

 

posted @ 2021-01-11 16:28  超哥20  阅读(1337)  评论(0编辑  收藏  举报