繁体   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