为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

白衣非少年 2023-11-11 16:06:17
我有 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"}
查看完整描述

2 回答

?
慕雪6442864

TA贡献1812条经验 获得超5个赞

如果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);


查看完整回答
反对 回复 2023-11-11
?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

如果需要在对象之间进行深度相等检查,那么我们可以使用 lodash 与andisEqual一起进行深度相等检查:Array#filterArray#some


let arr1 = [    

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

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

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

 ]


let arr2 = [

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

]


const filterArr = (arr1, arr2) =>{

  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>


查看完整回答
反对 回复 2023-11-11
  • 2 回答
  • 0 关注
  • 56 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信