从数组中删除与另一个对象数组相同的对象

我有 2 个对象数组array 1,我想从 中array 2删除 的对象。我可以同时删除 1 个以上的对象。array 2array 1


数组1的数据


let arr1 = [    

    { id: "1", txt: "first"},

    { id: "2", txt: "second"},

    { id: "3", txt: "third"}

 ]

数组2的数据


let arr2 = [

    { id: "2", txt: "second"},

]

结果


{ id: "1", txt: "first"},

{ id: "3", txt: "third"}


白衣非少年
浏览 104回答 2
2回答

慕雪6442864

如果id属性是唯一的,您可以用它过滤掉。let arr1 = [        { id: "1", txt: "first"},    { id: "2", txt: "second"},    { id: "3", txt: "third"} ]let arr2 = [    { id: "2", txt: "second"},]let arr3 = arr1.filter(e1 => !arr2.some(e2 => e2.id === e1.id));console.log(arr3);

白猪掌柜的

如果需要在对象之间进行深度相等检查,那么我们可以使用 lodash 与andisEqual一起进行深度相等检查:Array#filterArray#somelet arr1 = [&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; { id: "1", txt: "first"},&nbsp; &nbsp; { id: "2", txt: "second"},&nbsp; &nbsp; { id: "3", txt: "third"}&nbsp;]let arr2 = [&nbsp; &nbsp; { id: "2", txt: "second"},]const filterArr = (arr1, arr2) =>{&nbsp; return arr1.filter(a1 => !arr2.some(a2 => _.isEqual(a1, a2)))}console.log(filterArr(arr1, arr2))<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript