如何通过使用ES6从两个对象数组中删除重复项

时间:2019-02-12 05:27:59

标签: javascript arrays node.js ecmascript-6 es6-promise

我正在尝试从userPermitDataArr中删除重复项。

deniedModuleArr = [ { moduleName: 'Transaction fee',
    url: '/transactionfee',
    moduleClassName: 'TransactionFee' },
  { moduleName: 'Refund View',
    url: '/refundview',
    moduleClassName: 'RefundView' } ]

userPermitDataArr = [ { moduleName: 'Transaction fee',
    url: '/transactionfee',
    moduleClassName: 'TransactionFee' },
  { moduleName: 'Refund View',
    url: '/refundview',
    moduleClassName: 'RefundView' },
  { moduleName: 'Cancellation',
    url: '/cancellation',
    moduleClassName: 'Cancellation' },
  { moduleName: 'Transaction',
    url: '/transaction',
    moduleClassName: 'Transaction' } ]


 [{ moduleName: 'Cancellation',
    url: '/cancellation',
    moduleClassName: 'Cancellation' },
  { moduleName: 'Transaction',
    url: '/transaction',
    moduleClassName: 'Transaction' } ]

2 个答案:

答案 0 :(得分:2)

从命名约定和预期结果来看,您似乎需要从用户许可模块中过滤出拒绝的模块。您可以尝试关注。

首先根据上面创建的集合创建userPermitDataArr的{​​{3}},然后创建Set userPermitDataArr

let deniedModuleArr = [{ moduleName: 'Transaction fee',url: '/transactionfee',moduleClassName: 'TransactionFee' },{ moduleName: 'Refund View',url: '/refundview',moduleClassName: 'RefundView' } ];
let userPermitDataArr = [ { moduleName: 'Transaction fee',url: '/transactionfee', moduleClassName: 'TransactionFee' },{ moduleName: 'Refund View',url: '/refundview',moduleClassName: 'RefundView' },{ moduleName: 'Cancellation',url: '/cancellation',moduleClassName: 'Cancellation' },{ moduleName: 'Transaction',url: '/transaction',moduleClassName: 'Transaction' } ];
    
let deniedModuleSet = deniedModuleArr.reduce((a,c) => a.add(c.moduleName), new Set());
userPermitDataArr = userPermitDataArr.filter(v => !deniedModuleSet.has(v.moduleName));
console.log(userPermitDataArr);

答案 1 :(得分:0)

使用HashSet这种方法也可以用于检查嵌套结构的对象相等性。

const aStr = firstArr.map(o => JSON.stringify(o));
const bStr = secondArr.map(o => JSON.stringify(o));

const set = new Set();
set.add(...aStr);
set.add(...bStr);

console.log([...set.values()].map(o => JSON.parse(o)));