Brian Z Brian Z - 5 months ago 6
Javascript Question

Check if any object in an array of objects contains all of the key/value pairs in another object

I'm trying to write a function that looks through an array of objects (the first argument) and returns an array of all objects that contain all of the key/value pairs of a given object (the second argument).

My code below works only if the

source
object (the second argument) contains one key/value pair. When the
source
object has two or more key/value pairs, the result isn't as expected.

How to account for more than one key/value pair in the
source
object?

function findObjects(collection, source) {
var result = [];

for (i=0; i<collection.length; i++) {
for (var prop in source) {
if (collection[i].hasOwnProperty(prop) && collection[i][prop] == source[prop]) {
console.log('Collection\'s object ' + [i] + ' contains the source\'s key:value pair ' + prop + ': ' + source[prop] + '!');
result.push(collection[i]);
} else {
console.log('fail');
}
}
}

console.log('The resulting array is: ' + result);
return result;
}

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

// only the first object should be returned since it contains both "a":1 and "b":2

Answer
function findObjects(collection, source) {
    var result = [];

    for (i=0; i<collection.length; i++) {
        var matches = true;
        for (var prop in source) {
            if (!collection[i].hasOwnProperty(prop) || collection[i][prop] !== source[prop]) {
                matches = false;
                break;
            }
        }
        if (matches) {
            result.push(collection[i]);
        }
    }
    return result;
}

Basically, you have to check ALL properties and make sure they match, and then only then do you add it to your result array.