Reputation: 107
I'm a total novice with jQuery (and javascript in general!), so with that in mind please be merciful! :)
I'm trying to pull information from a JSON database, to do that I've created a search box and I've managed to source a solution for requesting the data that seems to work perfectly if I type in the EXACT thing I am looking for. But obviously I would like to have it so that the user doesn't need to worry about case matching.
I figured the most sensible thing to do would be to use some sort of fuzzy search but so far my efforts have resulted in exactly squat!
Here is the function that pulls the data:
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
And here is the nightmare that is my attempt to deal with that information:
$.getJSON("json/AllSets.json",function(hearthStoneData){
$('.submit').click(function(){
var searchValue = $('#name').val();
var inputValue = searchValue.toUpperCase();
var returnValue = getObjects(hearthStoneData, "name", searchValue);
var outputValue = returnValue.toString();
console.log(outputValue);
});
});
Does anybody have any advice on where I'm going wrong? I think I've gone waaaay off the beaten path with all the variables in the last part, I was trying to set both user input and the returned data to upper case but I think the fuzzy search option would make more sense?
Anyway, I appreciate any help you can offer, thanks for taking the time to read through what I imagine is some very confused code :P
Upvotes: 1
Views: 245
Reputation: 2863
Possible solution is to test a match using only lowercase in the val check:
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key].toLowerCase() == val.toLowerCase()) {
objects.push(obj[i]);
}
}
return objects;
}
//edited to include harvtronix' input.
Upvotes: 2