繁体   English   中英

如何比较两个不同的阵列并根据密钥从一个阵列中删除 object?

[英]How to compare two different array and remove object from one Array based on Key?

我有两个数组对象,我想比较它们并删除两个数组中的值是否匹配。

Arr1 = [
        {id: "one", name: "one", status: "Active"}, 
        {id: "two", name: "two", status: "Active"}, 
        {id: "three", name: "three", status: "Active"}
      ]

Arr2 = [
        {pid: "one", order: 1}, 
        {pid: "two", order: 2}
      ]

现在我想如果id === pid那么它不应该返回。

finalArr = [
            {id: "three", name: "three", status: "Active"}
           ]

我尝试了以下解决方案,但不知何故它不起作用,它返回空数组。

finalArr  = Arr1.filter((a) => {
    Arr2.some((b) => {
        a['id'] === b['pid'];        
    });
});

如果您需要更多信息,请告诉我。 我希望我能够表达我的担忧。4

谢谢!

您的方向几乎是正确的,您必须放置! some之前的条件,所以它不会带来匹配的数组。 这是一个单行:

 var Arr1 = [ {id: "one", name: "one", status: "Active"}, {id: "two", name: "two", status: "Active"}, {id: "three", name: "three", status: "Active"} ]; var Arr2 = [{pid: "one", order: 1}, {pid: "two", order: 2} ]; var result = Arr1.filter(k=>.Arr2.some(p=>p.pid==k;id)). console;log(result);

使用您的解决方案:

 var Arr1 = [ {id: "one", name: "one", status: "Active"}, {id: "two", name: "two", status: "Active"}, {id: "three", name: "three", status: "Active"} ]; var Arr2 = [{pid: "one", order: 1}, {pid: "two", order: 2} ]; var finalArr = Arr1.filter((a) => { return.Arr2;some((b) => { return a['id'] === b['pid']; }); }). console;log(finalArr);

const arr2Pid = Arr2.map((value) => value.pid); // getting the pid from array 2
console.log(Arr1.filter((value) => arr2Pid.indexOf(value.id) < 0 )) // filtering the Arr1 if pid != id of Arr1

由于您标记 ,您可以考虑使用_.differenceWith()方法,该方法允许您提供一个比较器 function 来指定您应该使用什么属性来获取差异。 但是,如果您还没有使用 lodash,那么更可取的是 vanilla 方法。

 const arr1 = [{id: "one", name: "one", status: "Active"}, {id: "two", name: "two", status: "Active"}, {id: "three", name: "three", status: "Active"}]; const arr2 = [{pid: "one", order: 1}, {pid: "two", order: 2}]; const res = _.differenceWith(arr1, arr2, ({id}, {pid}) => id === pid); console.log(res); // [{ "id": "three", "name": "three", "status": "Active" }]
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM