我有一个搜索结果页面,其中包含用户已搜索过的搜索结果。在此页面中,我们还提供了过滤选项,可以缩小现有搜索范围,例如:用户可以过滤搜索结果(按价格范围,按品牌,按类别和更多标准)。如果此数据在浏览器上的json对象中可用。如何根据上述几个标准过滤json数据。
例如 用户搜索液晶电视和所有类型的液晶电视将显示在搜索页面上,但用户可以通过以下选项过滤掉结果。
过滤选项
按品牌分类 - 三星,LG,索尼,JVC,海尔,Bose,Hundayi
价格 - 价格范围滑块100 $ - 5000 $
最畅销 -
按尺寸-39英寸,49英寸,72英寸
这里是json数据样本
{
"productList" : {
"product details" : [
{
"brand":"Lg",
"productname":"Microwave",
"price":200
},
{
"brand":"Samsung",
"productname":"Digi cam",
"price":120
},
{
"brand":"Sony",
"productname":"Lcd TV",
"price":3000
},
{
"brand":"LG",
"productname":"Flat TV",
"price":299
}
,
{
"brand":"Samsung",
"productname":"Lcd TV",
"price":700
},
{
"brand":"LG",
"productname":"Plasma TV",
"price":3000
},
{
"brand":"sony",
"productname":"Plasma TV",
"price":12929
}
]
}
}
答案 0 :(得分:3)
这不是很灵活,但这样的事情可能符合您的需求: Working Example
数据存储的过滤功能
// dataStore = JSON object, filter = filter obj
function filterStore(dataStore, filter) {
return $(dataStore).filter(function(index, item) {
for( var i in filter ) {
if( ! item[i].toString().match( filter[i] ) ) return null;
}
return item;
});
}
使用
// result contains array of objects based on the filter object applied
var result = filterStore( store, filter);
我拥有的数据存储
var store = [
{"brand": "Lg",
"productname": "Microwave",
"price": 200},
{"brand": "Samsung",
"productname": "Digi cam",
"price": 120},
{"brand": "Sony",
"productname": "Lcd TV",
"price": 3000},
{ "brand": "LG",
"productname": "Flat TV",
"price": 299},
{"brand": "Samsung",
"productname": "Lcd TV",
"price": 700},
{"brand": "LG",
"productname": "Plasma TV",
"price": 3000},
{"brand": "sony",
"productname": "Plasma TV",
"price": 12929}
];
过滤我用过的对象
// RegExp used could most likely be improved, definitely not a strong point of mine :P
var filter = {
"brand": new RegExp('(.*?)', 'gi'),
"productname": new RegExp('(.*?)', 'gi'),
"price": new RegExp('299', 'gi')
};
var filter2 = {
"brand": new RegExp('LG', 'gi'),
"productname": new RegExp('(.*?)', 'gi'),
"price": new RegExp('(.*?)', 'gi')
};
var filter3 = {
"brand": new RegExp('Samsung', 'gi'),
"productname": new RegExp('(.*?)', 'gi'),
"price": new RegExp('(.*?)', 'gi')
};
var filter4 = {
"brand": new RegExp('(.*?)', 'gi'),
"productname": new RegExp('Plasma TV', 'gi'),
"price": new RegExp('(.*?)', 'gi')
};
答案 1 :(得分:2)
尝试
// jsonData = [{"brand": "LG"}, {"brand": "Samsung"}]
jsonData.sort(brand);
// render the grid html again
修改强>
// you dont require sorting then
var dataBrand = Array();
$.each(jsonData, function() {
if(this.brand=="LG") dataBrand[this.brand] = this;
});