Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 16:00
Show Gist options
  • Save rfprod/b3ec8bd4a1935cbe8373 to your computer and use it in GitHub Desktop.
Save rfprod/b3ec8bd4a1935cbe8373 to your computer and use it in GitHub Desktop.
Where Art Thou
function where(collection, source) {
var arr = [];
var checker = Object.keys(source);
var checkerValue = source[checker];
var keysCollectionLength = Object.keys(collection).length;
var toCheck;
var outputCollectionKeys = [];
for (var i=0;i<keysCollectionLength;i++){
toCollection = Object.keys(collection[i]);
toCheck = collection[i][checker];
var collectionLength = collection[i].length;
if ((toCheck == checkerValue)&&(toCollection.length >= checker.length)){
arr.push(collection[i]);
}
}
return arr;
}
where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 });

Where Art Thou

A function that looks through an array of objects (first argument) and returns an array of all objects that have matching property and value pairs (second argument). Each property and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array. For example, if the first argument is [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], and the second argument is { last: "Capulet" }, then function returns the third object from the array (the first argument), because it contains the property and it's value, that was passed on as the second argument.

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment