I want to filter and search through Json using multiple keywords. I have it working when there is only one value to check against, but I need to use multiple keyword search filters.
In this example, I want to return the objects related to Wal-mart and China but NOT Wal-Mart in the US or Target in China.
I create an array of keywords to filter using Grep() and Map that out in console. I cannot figure out the syntax to check the value against the keyword however (see my comment below, "This is not right.")
<!DOCTYPE html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script>
var keywords = ["China", "Wal-Mart"];//filter Json by these terms
var data = [
{
"name": "Store #1",
"country": "China",
"retailer": "Wal-Mart"
},
{
"name": "New Store #2",
"country": "China",
"retailer": "Wal-Mart"
},
{
"name": "Store Name US",
"country": "United States",
"retailer": "Wal-Mart"
},
{
"name": "Target #98237",
"country": "China",
"retailer": "Target"
}
]
var searchkeywords = $.grep(data, function(value,i) {
return value[i] === keywords[i];//<--- This is not right
//should be the equivalent of above keywords:
//return value.country.toLowerCase() === "china" && value.retailer.toLowerCase() === "wal-mart"
});
var keywordsearchresult = $.map(searchkeywords, function(value, i) {
return {
name: value.name,
country: value.country,
retailer: value.retailer
};
});
console.log(keywordsearchresult);//should return first 2 items
</script>
</head>
<body>
</body>
</html>
In my application, there will be more keywords and items (type, date, etc..) in the Json, this is just a simplified version. I basically want to add a lot of rules and conditions to the Grep.