簡體   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