简体   繁体   中英

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

I have an array given with multiple objects as entries (collection) and I want to check if another source object is in those single entry objects. If so I want to return an array with all the objects that fulfill that condition. Here is the code with an example:

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 }));

Obviously I don't know what to put where it's written ("what happens here"). The problem is basically that the second for loop and both if conditions have to be true so the push command makes sense.

I appreciate any hint or help , thanks!

PS I know that this is probably not the most elegant way to solve it so happy about any other solutions as well.

This is where the built-in .filter function comes in handy:

 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 })); 

Or, if you're inclined to use a library to do this, it can be done very simply with 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM