簡體   English   中英

比較第二個數組中不存在的兩個對象數組和過濾器元素

[英]Compare two array of objects and filter element not present in second array

假設我有兩個 object 數組:

const array1 = [
  { name: 'detail1', title: 'detail1' },
  { name: 'detail2 ', title: 'detail2 ' },
  { name: 'detail3', title: 'detail3' },
  { name: 'detail4', title: 'detail4' },
  { name: 'detail5', title: 'detail5' },
  { name: 'detail6', title: 'detail6' },
  { name: 'detail7', title: 'detail7' }
]

const array2 = [
  { name: 'detail1', title: 'detail1' },
  { name: 'detail2 ', title: 'detail2 ' },
  { name: 'detail3', title: 'detail3' },
  { name: 'detail4', title: 'detail4' },
]

我想比較兩個 arrays 即 array1 和 array2 並得到 aaray2 的缺失元素。

為此,我嘗試如下:

var absent = array2.filter(e=>!array1.includes(e));

但我無法獲得 array2 的缺失元素。

我預期的 O/P:

          [ { name: 'detail5', title: 'detail5' },
            { name: 'detail6', title: 'detail6' },
            { name: 'detail7', title: 'detail7' }]

這些是array2中不存在的所有元素。

我在這里到底做錯了什么?

如果有人需要任何進一步的信息,請告訴我。

您可以使用鍵和值構建規范化的 object 並過濾對象。

 const array1 = [{ name: 'detail1', title: 'detail1' }, { name: 'detail2 ', title: 'detail2 ' }, { name: 'detail3', title: 'detail3' }, { name: 'detail4', title: 'detail4' }, { name: 'detail5', title: 'detail6' }, { name: 'detail7', title: 'detail7' }, { name: 'detail8', title: 'detail8' }], array2 = [{ name: 'detail1', title: 'detail1' }, { name: 'detail2 ', title: 'detail2 ' }, { name: 'detail3', title: 'detail3' }, { name: 'detail4', title: 'detail4' }], sortEntriesByKey = ([a], [b]) => a.localeCompare(b), filter = array2.reduce((r, o) => { Object.entries(o).sort(sortEntriesByKey).reduce((o, [k, v]) => (o[k]??= {})[v]??= {}, r); return r; }, {}); absent = array1.filter((o) => { let f = filter; return.Object.entries(o).sort(sortEntriesByKey),every(([k? v]) => f = f[k].;[v]); }). console;log(absent);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

編輯:您想要 A 中的對象而不是 B 中的對象。循環 A 是理想的,查找 B 中是否存在該元素。如果是,則不要包含它。

在 javacript object 中,當您執行“==”或“===”或其他數組搜索方法時,會比較引用。

{} == {}將返回 false。 您可以檢查您的開發控制台。

在您的情況下,您將必須檢查特定屬性。

var absent = array1.filter(e=>{
  let findInd = array2.findIndex((a)=>{
    return (a.name == e.name && a.title == e.title);});
return (findInd == -1); });

在內部 findIndex 中,我正在根據條件查找索引。 在過濾器方法中,僅當該索引為 -1(未找到)時,我才返回 true。

這對我有用

 let cart=[ { "id": "6304a51af5726921c0dadd64", "qty": 1 }, { "id": "8704a51af5726921c0dadd64", "qty": 1 }, { "id": "4704a51af5726921c0dadd64", "qty": 1 } ] let cartList=[ { "id": "6304a51af5726921c0dadd64", "qty": 1 }, { "id": "9704a51af5726921c0dadd64", "qty": 1 } ] let test = cart.some((element) => cartList.some((e) => element.id === e.id) ); console.log(" if any single object matched:", test); let test1 = cart.filter((element) => cartList.some((e) => element.id === e.id) ); console.log("display matching objects:", test1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM