我有两个对象数组,想要找到第二个数组中缺少但属于第一个数组的一部分的项目,基本上是 array1-array2。我尝试使用过滤器,但无法获得所需的结果。请帮忙。提前致谢。
这是代码:
testData=[
{id: 0, name: "policy001"},
{id: 2, name: "policy002"}];
sourceData= [
{id: 0, name: "policy001"},
{id: 2, name: "policy002"},
{id: 3, name: "policy003"},
{id: 4, name: "policy004"},
{id: 5, name: "policy005"},
];
let missing = sourceData.filter(item => testData.indexOf(item) < 0);
console.log("Miss")
console.log(missing )//Returns the sourceData instead of diff.
最佳答案
尝试findIndex()
:
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.
testData = [{
id: 0,
name: "policy001"
},
{
id: 2,
name: "policy002"
}
];
sourceData = [{
id: 0,
name: "policy001"
},
{
id: 2,
name: "policy002"
},
{
id: 3,
name: "policy003"
},
{
id: 4,
name: "policy004"
},
{
id: 5,
name: "policy005"
},
];
console.log(sourceData.filter(item => testData.findIndex(x => x.id == item.id) < 0))
关于javascript - 两个对象数组的 typescript 差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56071815/