簡體   English   中英

如何在不使用方法的情況下檢查對象是否包含對象?

[英]How do I check if an object contains an object without using methods?

我正在嘗試檢查對象中是否包含具有部分匹配樣式的另一個對象。

因此,下面的示例一旦工作,就應該在myArray兩次找到對象{'a':{'b':'c'} 請注意,即使myArray[0]對象在{'a':{'b':'c'}之上還具有'e': 'f'的附加屬性,仍應認為它包含{'a':{'b':'c'}

我想避免使用任何方法,例如reduce或map。

 const myArray = [ { 'a': { 'b': 'c', 'e': 'f', } }, { 'a': { 'b': 'c' } }, { 'd': { 'e': 'f' } }, ] function contains(array, index, object) { if () { // implementation??? return true } else { return false } } function quantityOfObjectInArray(object, array) { var count = 0; for (var i = 0; i < this.length; ++i) { if ( contains(array, i, object) ) { count++; } } return count } var quantity = quantityOfObjectInArray({'a':{'b':'c'}}, myArray) console.log(quantity) // expect: 2 

您可以使用Object.entries遞歸比較對象:

function has(obj, proto) {
  for(const [key, value] of Object.entries(proto)) {
    if(typeof value === "object") {
      if(!obj[key] || !has(obj[key], value))
         return false;
    } else if(obj[key] !== value) {
      return false;
    }
  }
  return true;
}

暫無
暫無

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

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