簡體   English   中英

如何檢查數組的所有對象是否包含在另一個數組中?

[英]How to check if all objects of array are included another array?

我試圖檢查對象array A包含來自B objects

let A = [
    { name: "Max" },
    { name: "Jhon" },
    { name: "Naton" },
]

let B = [
    { name: "Max" },
    { name: "Naton" },
]

所以B有兩個objectsarray A 怎么檢查這個?

我試圖通過includes

  for(let entry of this.b){
      if(this.a.includes(entry)){
        console.log('includes');
      }
    }

但是我對includes false

您必須使用另一個循環,然后檢查屬性名稱:

 var a = [ {name: "Max"}, {name: "Jhon"}, {name: "Naton"}, ]; var b = [ {name: "Max"}, {name: "Naton"}, ]; for(let entry of b){ for(let entry2 of a){ if(entry2.name == entry.name){ console.log('includes', entry.name); } } } 

或者:您可以使用對象的字符串版本來檢查includes()

 var a = [ {name: "Max"}, {name: "Jhon"}, {name: "Naton"}, ]; var b = [ {name: "Max"}, {name: "Naton"}, ]; var aTemp = a.map(i => JSON.stringify(i)); var bTemp = b.map(i => JSON.stringify(i)); for(let entry of bTemp){ if(aTemp.includes(entry)){ console.log('includes', entry); } } 

方法Array.includes()將數組的條目與給定值進行比較。 因為您的數組條目是對象,所以它不匹配。 你必須自己循環數組並進行比較。

Array.some()在數組上循環,如果返回true至少為1,則返回true。 當您想要驗證某些內容時,此方法很有用。 在我們的示例中,我們要驗證數組a是否包含b條目。

 const a = [{ name: 'Max', }, { name: 'Jhon', }, { name: 'Naton', }, ]; const b = [{ name: 'Max', }, { name: 'Naton', }, { name: 'Daddy', }, ]; console.log(b.map(x => a.some(y => y.name === x.name))); 


如果我把它分解:

 const a = [{ name: 'Max', }, { name: 'Jhon', }, { name: 'Naton', }, ]; const b = [{ name: 'Max', }, { name: 'Naton', }, { name: 'Daddy', }, ]; // Loop on every entry of the b array b.forEach((x) => { // x here represent one entry // first it will worth { name: 'Max' }, then { name: 'Naton' } ... // for each value we are going to look at a if we can find a match const isThereAMatch = a.some((y) => { // y here is worth one entry of the a array if (y.name === x.name) return true; return false; }); if (isThereAMatch === true) { console.log(`We have found ${x.name} in a`); } else { console.log(`We have not found ${x.name} in a`); } }); 

當您使用Array#includes()方法時 ,它將始終返回false 因為它正在比較不相等的objects因為它們沒有引用同一個object

您應該比較對象properties而不是整個對象,您可以使用Array#some()方法來執行此操作,如下所示:

for (let entry of this.b) {
  if (this.b.some(x => x.name === entry.name)) {
    console.log('includes');
  }
}

演示:

 A = [{ name: "Max" }, { name: "Jhon" }, { name: "Naton" }, ] B = [{ name: "Max" }, { name: "Naton" }, ] //Filter objects that exists in both arrays let result = A.filter(el=> B.some(x => x.name === el.name)); console.log(result); 

暫無
暫無

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

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