Reputation: 6865
I have this (shortened for question) JSON file:
[
{
"product":"aardappelen gebakken",
"quantity":"100gr",
"carbohydrates":"19,3"
},
{
"product":"aardappelen pikant",
"quantity":"100gr",
"carbohydrates":"3"
},
{
"product":"aardappelmeel",
"quantity":"100gr",
"carbohydrates":"80"
}
]
Wat i want to do is:
search for a product, and result all of its content, like when i would search for "aardappelmeel", i get product, quantity and carbohydrates key value, i do this with this code:
the search term is hardcoded for the moment, this will be a var later one.
$(function() {
$.getJSON( "js/data.json").fail(function(jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
}).done(function(data) {
var carbohydratesResult = getCarbohydrates(data, 'aardappelmeel');
console.log(carbohydratesResult);
});
});
function getCarbohydrates(arr, searchTerm){
var result;
if(searchTerm === '') {
result = 'No searchterm';
}
else {
result = _.where(arr, {product: searchTerm});
}
return result;
}
This gets 1 result:
Question: When i search for "aardappelen", i get no result, and it should be 2, because there are 2 products that contain the name "aardappelen". How do i do this?
I use jQuery, Underscore. If Underscore is not needed for this, fine by me, please show me how i modify my code to get more then one result when "product" value contains the search term.
Upvotes: 1
Views: 4141
Reputation: 102763
You need _.filter
along with indexOf
to do a substring search:
result = _.filter(arr, function(item) {
return item.product && item.product.indexOf(searchTerm) != -1;
});
Note that _.where
performs an exact match.
Upvotes: 2
Reputation: 621
I would probably say underscore is not needed for this (not optimal to include an entire js library just use use a single function). Searching for text simply in JavaScript is never fun. You're probably best writing some regex function that loops over your result set and tries to match some text.
If possible, I would try to implement the searching functionality on the server side, and return those results in an ajax request.
Rough example of a JS Solution...
var searchText = 'blah',
matches = [];
for(var i = 0; i < results.length; i++) {
var reg = new RegExp(searchText);
if(results[i].product.match(reg)) matches.push(results[i]);
}
return matches;
Upvotes: 1