1
let arr1 = [ 
    {fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
    {fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"},
    {fpcid: "2da37fdfe66140089dc3367b21cc6196", fpcNameCode: "35"},
    {fpcid: "2da37fdfe66140089dc3367b21cc6197", fpcNameCode: "36"}
];
let arr2 = [ 
    {fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
    {fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"}
];



JS求两个对象数组的差集

[
        {fpcid: "2da37fdfe66140089dc3367b21cc6196", fpcNameCode: "35"},
        {fpcid: "2da37fdfe66140089dc3367b21cc6197", fpcNameCode: "36"}
]
2019-04-28 提问

查看全部 5 个回答

0

对于这种值为基础类型的对象,可以试一下JSON.stringify(),转换成JSON字符串处理更方便点

推荐答案

0

已采纳

先上代码:

{
            let arr1 = [
                { fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34" },
                { fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33" },
                { fpcid: "2da37fdfe66140089dc3367b21cc6196", fpcNameCode: "35" },
                { fpcid: "2da37fdfe66140089dc3367b21cc6197", fpcNameCode: "36" }
            ];
            let arr2 = [
                { fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34" },
                { fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33" }
            ];
            
            function getDifferenceSetA(arr1, arr2) {
                arr1 = arr1.map(JSON.stringify);
                arr2 = arr2.map(JSON.stringify);
                return arr1.concat(arr2).filter(function (v, i, arr) {
                    return arr.indexOf(v) === arr.lastIndexOf(v);
                }).map(JSON.parse)
            }
            
            function getDifferenceSetB(arr1,arr2,typeName){
                return Object.values(arr1.concat(arr2).reduce((acc,cur) => {
                    if (acc[cur[typeName]] && acc[cur[typeName]][typeName] === cur[typeName]) {
                        delete acc[cur[typeName]];
                    }else{
                        acc[cur[typeName]] = cur;
                    }
                    return acc ;
                },{}));
            }
            

            console.log('getDifferenceSetA:',getDifferenceSetA(arr1,arr2));
            console.log('getDifferenceSetB:',getDifferenceSetB(arr1,arr2,'fpcid'));

        }

输出结果如下图:
clipboard.png

两种方案比较,A方案比较取巧,使用起来方便快捷,但有个问题,对于值不为基础类型的对象可能产生一些不可预知的报错
B方案比较稳定,可以适应各种对象比较,但写法和逻辑相对A稍微复杂点。

推广链接