如何在JavaScript中删除对象数组中的重复对象

时间:2019-10-22 15:18:19

标签: javascript arrays

我想删除重复的对象。我该怎么办?

const array1 = [{ currencyName : "USD", code: "121" }, 
                { currencyName : "INR", code: "123" }];

const array2 = [{ currencyName : "USD", code: "121" }];

Result = [{ currencyName : "INR", code: "121" }]

2 个答案:

答案 0 :(得分:0)

尝试使用filtersome方法:

const array1 =[ 
    { currencyName : "USD", code: "121" }, 
    { currencyName : "INR", code: "123" }
]

const array2=[ { currencyName : "USD", code: "121" }];

const result = array1.filter(f=> 
    !array2.some(s=> f.code === s.code && f.currencyName === s.currencyName)
);

console.log(result)

答案 1 :(得分:0)

const array1 = [{
  currencyName: "USD",
  code: "121"
}, {
  currencyName: "INR",
  code: "123"
}, ]

const array2 = [{
  currencyName: "USD",
  code: "121"
}, {
  currencyName: "FRA",
  code: "122"
}]

let array1Uniques = array1.filter(a => !array2.some(b => b.code === a.code));
let array2Uniques = array2.filter(a => !array1.some(b => b.code === a.code));
let result = [...array1Uniques,  ...array2Uniques];
console.log(result);