I am trying to build a small search function where I can search through some JavaScript objects even if there are arrays in it. I got it working but I would like to ask if someone can find a better approach than the one I made. Also, I assume I have some cases I did not think of.
My current search function looks as follows:
function searchFor(needle, haystack, filter, inside){
if (inside == undefined) inside = 1;
if (filter){
for (var c = 0; c < filter.length; c++) {
var splittedFilter = filter[c].split('.');
for (var s = 0; s < splittedFilter.length; s++) {
var obj = haystack[splittedFilter[s]];
if (obj){
if (Array.isArray(obj) && obj.length > 0){
for (var i = 0; i < obj.length; i++) {
var result = searchFor(needle, obj[i], [splittedFilter[inside]], inside+1);
if (result) return true;
}
} else if( typeof obj == "object"){
var result = searchFor(needle, obj, [splittedFilter[inside]], inside+1);
if (result) return true;
} else {
if (obj.toLowerCase().indexOf(needle.toLowerCase()) != -1){
return true;
}
}
}
}
}
}
return false
}
The filterlist:
var filter = ['company', 'friends.name'];
The haystack:
var hay = [
{
"id": "57db96f4acfaec3218383063",
"name": {
"first": "Nora",
"last": "Cooke"
},
"company": "MITROC",
"email": "[email protected]",
"friends": [
{
"id": 0,
"name": "West Duke"
},
{
"id": 1,
"name": "Williams Kelley"
},
{
"id": 2,
"name": "Amelia Kirk"
}
]
},
{
"id": "57db96f4d5cae409054d3a5b",
"name": {
"first": "Dickson",
"last": "Moses"
},
"company": "VISUALIX",
"email": "[email protected]",
"friends": [
{
"id": 0,
"name": "Patty Carr"
},
{
"id": 1,
"name": "Bowers Wilkerson"
},
{
"id": 2,
"name": "Fox Kidd"
}
]
}
];
The execution of the search function:
hay.forEach(function(element) {
if (searchFor('Duke', element, filter)) {
document.getElementById('result').innerHTML = document.getElementById('result').innerHTML + '<br />' + JSON.stringify(element);
}
}, this);
- needle is the string to search for
- haystack is one object
- filter is an array of filters, like:
var filter = ['company']; - inside is to determine how far in the recursive loop the function is
I made a live example here.