Last active
August 29, 2015 14:06
-
-
Save kishmiryan-karlen/9af1f906b6a0920eb2f3 to your computer and use it in GitHub Desktop.
A function written in pure JavaScript, which allows to find an object in array of objects using another object or array of objects as a query.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function search(searchQuery, data) { | |
if(searchQuery instanceof Array) { | |
return searchQuery.reduce(function(prev, current, index, array) { | |
return prev.concat(search(current, data)); | |
}, []); | |
} | |
var results = data.filter(function(el) { | |
for(var prop in searchQuery) { | |
if(searchQuery[prop] instanceof Array) { | |
if(searchQuery[prop].indexOf(el[prop]) == -1) { | |
return false; | |
} | |
} else if(el[prop] !== searchQuery[prop]) { | |
return false; | |
} | |
} | |
return true; | |
}); | |
return results; | |
}; | |
// Example array of objects | |
var users = [ | |
{"id":1,"gender":"M","first":"John","last":"Smith","city":"Seattle, WA","status":"Active"}, | |
{"id":2,"gender":"F","first":"Kelly","last":"Ruth","city":"Dallas, TX","status":"Active"}, | |
{"id":3,"gender":"M","first":"Jeff","last":"Stevenson","city":"Washington, D.C.","status":"Active"}, | |
{"id":4,"gender":"F","first":"Jennifer","last":"Gill","city":"Seattle, WA","status":"Inactive"} | |
]; | |
// Example queries | |
// Ex. 1 - gender = M | |
var search_object = { gender:"M" }; | |
// Ex. 2 - gender = M and city = Seattle, WA | |
// var search_object = { gender:"M", city:"Seattle, WA" }; | |
// Ex. 3 - status = Active or status = Inactive | |
// var search_object = { status: [ "Active", "Inactive" ] }; | |
// Ex. 4 - status = Active or status = Inactive | |
// var search_array = [ { status: "Active" }, { status: "Inactive" } ]; | |
// Ex. 5 - status = Active or status = Inactive | |
// var search_array = [ { status : [ "Active", "Inactive" ] } ]; | |
search(search_object, users); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment