gpt4 book ai didi

javascript - 如何在浏览器上过滤Json数据?

转载 作者:行者123 更新时间:2023-11-29 09:59:31 25 4
gpt4 key购买 nike

我有一个搜索结果页面,其中包含用户已经搜索过的搜索结果,在此页面中,我们还有过滤器选项,可以缩小现有搜索范围,例如用户可以过滤搜索结果(按价格范围、按品牌、按类别和更多标准)。如果此数据在浏览器上的 json 对象中可用。我如何根据上述几个标准过滤 json 数据。

例如用户搜索液晶电视,所有类型的液晶电视都会显示在搜索页面上,但用户可以通过以下选项过滤掉结果。

过滤选项

按品牌 - Samsung、LG、Sony、JVC、Haier、Bose、Hundayi
Br 价格 - 价格范围 slider 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
}
]
}
}

最佳答案

这不是很灵活,但像这样的东西可能符合您的需要: 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')
};

关于javascript - 如何在浏览器上过滤Json数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4390396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com