簡體   English   中英

如何檢查JavaScript中的對象是否與多個對象組成數組?

[英]How to check in JavaScript if object is in array with multiple objects?

我有一個數組,給出了多個對象作為條目(集合),我想檢查另一個源對象是否在這些單個條目對象中。 如果是這樣,我想返回一個數組,其中包含所有滿足該條件的對象。 這是帶有示例的代碼:

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命令才有意義。

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

PS我知道這可能不是解決它的最優雅的方法,因此對其他任何解決方案也很滿意。

這是內置的.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> 

暫無
暫無

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

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