2017-06-01 37 views
1

我有一個數組給予多個對象作爲條目(集合),我想檢查另一個源對象是否在這些單個條目對象中。如果是這樣,我想返回一個數組,其中包含滿足該條件的所有對象。下面是一個例子代碼:如果對象與多個對象組成陣列,如何檢查JavaScript?

function whatIsInAName(collection, source) { 
    var arr = []; 
    var sourceEntries = Object.entries(source); 
    for (var i = 0; i < collection.length; i++) { 
     for (var j = 0; i < sourceEntries.length; i ++) { 
      if((collection[i].hasOwnProperty(sourceEntries[j][0]))) { 
       if(collection[i][sourceEntries[j][0]] == sourceEntries[j][1]) { 
        /*what happens here*/ 
       } 
      } 
     arr.push(collection[i]); 
     } 

    } 
    return arr; 
} 

print(whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })); 

很顯然,我不知道該怎麼把它的書面(「這裏是什麼情況」)。問題基本上是第二個for循環,如果條件必須是true,所以push命令纔有意義。

我很感激任何提示或幫助,謝謝!

P.S.我知道這可能不是最優雅的解決方案,因此對任何其他解決方案都很滿意。

+0

你可以給一個樣本輸入和輸出嗎?我認爲這可以幫助某人確切地瞭解您的需求。 –

+0

我的意思是取決於你真正想做得多徹底,你可以測試'JSON.stringify(item_in_array)== JSON.stringify(search_object)' – Jhecht

+0

當然,@ArnavAggarwal! 因此,基本上它在輸入語句中是什麼,輸出應該是: '[{「a」:1,「b」:2},{「a」:1,「b」:2,「c 「:3}]'因爲這兩個對象同時包含'a'和'b'。 –

回答

2

這是內置.filter功能就派上用場了:

function whatIsInAName(collection, source) { 
 
    return collection.filter((obj) => { 
 
    for (var prop in source) { 
 
     if (source[prop] !== obj[prop]) { 
 
     // The source property is not found in obj - no good! 
 
     return false; 
 
     } 
 
     // The source property matches one of the obj's properties - keep going! 
 
    } 
 
    // Made it through the checks! You've got a match! 
 
    return true; 
 
    }); 
 
} 
 

 
console.log(whatIsInAName([{ 
 
    "a": 1, 
 
    "b": 2 
 
}, { 
 
    "a": 1 
 
}, { 
 
    "a": 1, 
 
    "b": 2, 
 
    "c": 2 
 
}], { 
 
    "a": 1, 
 
    "b": 2 
 
}));

或者,如果你傾向於使用庫要做到這一點,就可以做到很簡單地Lodash

var collection = [{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], 
 
    source = { "a": 1, "b": 2 }; 
 

 
console.log(_.filter(collection, source));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

+0

謝謝,@ j-titus流暢而優雅的解決方法。非常感謝! –